<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Util\SqlServerUtil;
use App\Services\OSS;
use App\Util\Common;
use App;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\QueryException;

use Illuminate\Support\Facades\Session;

define('IS_OPEN_LOG', true);//false true
class YcangController extends CommonController
{

    protected $response = [
        "Error" => 0,
        "Message" => "Success!",
        "Data" => []
    ];
    
    //测试接口通信，或获取接口版本
    public function getVersion(Request $request){
		$this->log(__FUNCTION__,$request);
        $type = $request->get('tadmin');
        if(!empty($type)&&$type=='admin2020'){
            $sql="select FName,FlastTradeAmount,FlastRPAmount,FmaxDealAmount,FdebtLevel,FCarryingAOS,FSMSPhoneNumber from t_Organization where FName = '深圳市冰洋电子有限公司'";
			$sql = iconv('UTF-8', 'GBK', $sql);
			$res = SqlServerUtil::exec($this->SqlServer, $sql);
			returnData(0, 'Success!',$res); 
        }else{
            returnData(0, 'Success!',['version'=>'1.0']);
        }
    }
    private function array_unique_fb($array2D) {
        foreach ($array2D as $v) {
            $v = join(",", $v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
            $temp[] = $v;
        }
        $temp = array_unique($temp);//去掉重复的字符串,也就是重复的一维数组
        foreach ($temp as $k => $v) {
            $temp[$k] = explode(",", $v);//再将拆开的数组重新组装
        }
        return $temp;
    }
    
	//获取账套
    private function getdb(){
        $sql="SELECT 
                  [cacc_name] as text
                  ,[cdbname] as db
              FROM [master].[dbo].[t_kdaccount_gl]
            GO";
        $res_dbs = SqlServerUtil::exec($this->SqlServer, $sql);
		 if(!$res_dbs){
            	$res_dbs =[];
            }
			
        $sql="select COUNT(1) as ok  from Master..SysDatabases where name='AcctCtl'";
        $res_ok = SqlServerUtil::exec($this->SqlServer, $sql);
        //&&!empty($res_ok[0]['ok'])
        if(isset($res_ok[0]['ok'])){
            $sql="select FAcctName as text,FAcctNumber as db  from Master..t_ad_kdaccount_gl where 1=1 order by facctid";
            $res_dbs2 = SqlServerUtil::exec($this->SqlServer, $sql);
            if(!$res_dbs2){
            	$res_dbs2 =[];
            }
            $sql3="select FName as text,FNumber as db  from Master..T_C_Gongzi where 1=1 order by fid";
            $res_dbs3 = SqlServerUtil::exec($this->SqlServer, $sql3);
            if(!$res_dbs3){
            	$res_dbs3 =[];
            }
            $res_dbs2= array_merge($res_dbs2,$res_dbs3) ;
            if(is_array($res_dbs2) && count($res_dbs2)>0) {
                foreach ($res_dbs2 as $k => $v) {
                    array_push($res_dbs,$v);
                }
            }
            $res_dbs = self::array_unique_fb($res_dbs, SORT_REGULAR);
        }
        returnData(0,'Success!',$res_dbs);
    }
	//用户登录
    private function login(Request $request){
// 		$this->log(__FUNCTION__,$request);
		$user= $request ->username ?$request ->username : '';
        if(!isset($user) || empty($user)) returnData(1, '用户名不能为空！');
        
        $pwd= $request ->password ?$request ->password:'';
        
        $sql="select top 1 username as FName,password as pwd,id as fuid,last_session,qdtimeStatus,starttime,endtime,status  from gz_admin where 1 =1 and username='{$user}'";
        $sql = iconv('UTF-8', 'GBK', $sql);
        $res = SqlServerUtil::exec($this->SqlServer, $sql,2);
        if(empty($res)){
        	returnData(1, '登录失败,用户名或密码错误！');
        }
        if($res['status'] == 0 ){
        	returnData(1, ' 该账号已禁用');
        }
        if($res['pwd'] == base64_encode($pwd)){
			/* $authinfo = $this->checkaccessright('SYERP','Public','WEB',$user);
            if($authinfo !== true){
                returnData(1, $authinfo);
            } */
        	$last_session =Session::getId(); 
        	if(!empty($res['qdtimeStatus']) &&  $res['qdtimeStatus'] == 1){
        		if(!empty($res['starttime']) && !empty($res['endtime']) ){
        			$curDTRQ = getCurrentTime(4);
        			$nowTime = getCurrentTime();
        			$starttime = $curDTRQ.' '.$res['starttime'];
        			$endtime = $curDTRQ.' '.$res['endtime'];
        			if($starttime >= $nowTime or $nowTime >= $endtime ){
        				showMsg(1,'不在上下班时间内');
        			}
        		}else{
        			showMsg(1,'请设置上下班时间');
        		}
        	}
        	//日志记录保存
        	$temp=[
        		'session_id'=>$last_session,
        		'admin_id'=>$res['fuid'],
        			
        		'ip_address'=>real_ip(),
        		'user_agent'=>$_SERVER['HTTP_USER_AGENT'],
        		'browser_name'=>get_user_browser(),
        		'is_active'=>1,
        		'login_at'=>1,
        		'location'=>php_uname('s'),
        	];
        	SqlServerUtil::sqlsrvCreateTosql($this->SqlServer, 'gz_user_logins',$temp);
        	
        	Session::put('username', $res['FName']);
	
        	$is_auth1 = urlencode($user);
            $is_auth = $user;
            $request->session()->put("_is_auth",$is_auth1);
			$request->session()->put("_fuid",$res['fuid']);
            //$request->session()->setPreviousUrl($request->fullUrl());
            $request->session()->save();
            //Cookie::queue('wms_auth', $is_auth, $minutes = 300, $path = null, $domain = null, $secure = false, $httpOnly = false);
            //$auth = $request->cookie("is_auth");
            //$token = $request->session()->getId();
            $result=[];
	        //  $result =  $this->FQXMenu($request);
	        $setval = false;
	        //查询用户--权限组列表
	        $group3 = "select a.username,a.id,ug.groupid,g.fname fgroupname  from gz_user_group ug
	        left join gz_admin a  on a.id= ug.userid left join gz_group g on g.id= ug.groupid
	        where 1=1 and a.status =1  and a.username = '{$user}' and ug.groupid=1   ";
	        $usergroupList = SqlServerUtil::execToSql($this->SqlServer, $group3,2);
	        if($usergroupList){
	        	$setval = true;
	        }
	        
            $auth=[
                'token'=>$request->session()->get('_token'),
                '_is_auth'=>$request->session()->get('_is_auth','default'),
				'_fuid'=>$request->session()->get('_fuid','default'),
                'previous'=>$request->session()->get('_previous'),
            	//'result'=>$result,
            	'flookSet'=>$setval,
            ];
           // sqlsrv_query($this->SqlServer, "update gz_admin set last_session ='{$last_session}' where  id='{$res['fuid']}' ");
            returnData(0, '成功登录！',$auth);
        }
        returnData(1, '登录失败,用户名或密码错误！');
    }
    
    
    public function FQXMenu(Request $request){
    	$loginname = $request->username;//登录名称
    	if(empty($loginname)){
    		showMsg(1,'传参错误，登录名称');
    	}
    	//菜单列表
    	$sql = "select fobjecttype,fobjectid,fname,fdescription from gz_objecttype where fobjecttype>=90000 and fobjectid=0 and fobjecttype in (select distinct fobjecttype from gz_objectfunc where FObjHide=0) order by fobjecttype,fobjectid";
    	$menuData = SqlServerUtil::execToSql($this->SqlServer, $sql);
    	$menuTemp = $menuData;
    	$sql1 = "select distinct t1.fobjecttype,t1.fobjectid,t1.fname,t1.fdescription from gz_objecttype t1 where  t1.fobjectid>0 and t1.fobjectid in (select distinct fobjectid from gz_objectfunc where FObjHide=0 and FIndex=0) order by t1.fobjecttype,t1.fobjectid";
    	$menulistData = SqlServerUtil::execToSql($this->SqlServer, $sql1);
    	
    	$sql2 = "select FObjectType,FObjectID,FIndex,FAccessMask,FName from gz_objectaccesstype order by findex";
    	$menuDetail = SqlServerUtil::execToSql($this->SqlServer, $sql2);
    	
    	$result=[];
    	if($menuData && $menulistData && $menuDetail){
    		foreach ($menuData as $k=>$v )
    		{
    			foreach ($menulistData as $k1=>$v1 )
    			{
    				if($v['fobjecttype'] == $v1['fobjecttype']){
    					$menuData[$k]['children'][] = $v1;
    				}
    			}
    		}
    		
    		foreach ($menuData as $k2=>$v2 )
    		{
    			foreach ($v2['children'] as $k3 =>$v3)
    			{
    				foreach ($menuDetail as $k4 =>$v4)
    				{
    					if($v3['fobjecttype'] == $v4['FObjectType']  && $v3['fobjectid'] == $v4['FObjectID'] )
    					{
    						$menuData[$k2]['children'][$k3]['child'][] = $v4;
    					}
    				}
    			}
    		}
    		//dd($menuData);
    		//showMsg(0,'成功',$menuData );
    	}
    	//是否在系统管理员组
    	$groupSql = "select a.username,a.id from gz_user_group ug left join gz_admin a  on a.id= ug.userid where ug.groupid=1 and a.status =1 and a.username='{$loginname}'";
    	$groupData = SqlServerUtil::execToSql($this->SqlServer, $groupSql,2);
    	//系统管理组
    	if($loginname == 'manager' || in_array($loginname, $groupData) ){
    		return $menuData ;
    	}
    	
    	//用户是否属于哪个组 权限
    	$group1 = "select a.username,a.id,ug.groupid,g.fname from gz_user_group ug left join gz_admin a  on a.id= ug.userid left join gz_group g on g.id= ug.groupid  where a.username='{$loginname}' and a.status =1 order by ug.id desc ";
    	$groupTemp = SqlServerUtil::execToSql($this->SqlServer, $group1,2);
    	//dd($groupTemp);
    	if(empty($groupTemp)){
    		showMsg(0,'该用户没有设置权限',[]);
    	}
    	$groupid = $groupTemp['groupid'];//获取组 id
    	
    	// 		//查询组列表
    	// 		$group2 = "select id,fname from gz_group where id !=1  ";
    	// 		$groupList = SqlServerUtil::execToSql($this->SqlServer, $group2);
    	
    	// 		//查询用户--权限组列表
    	// 		$group3 = "select a.username,a.id,ug.groupid,g.fname fgroupname  from gz_user_group ug left join gz_admin a  on a.id= ug.userid left join gz_group g on g.id= ug.groupid  where 1=1 and a.status =1 and  ug.groupid !=1  ";
    	// 		$usergroupList = SqlServerUtil::execToSql($this->SqlServer, $group3);
    	
    	//组权限 - gz_AccessControl_group
    	
    	$acsql="select ac.FObjectType,ac.FObjectID,ac.FUserID as FGroupid,ac.Fsqlist ,g.fname from gz_AccessControl_group ac left join gz_group g on  g.id=ac.FUserID where ac.FUserID ='{$groupid}'  ";
    	$acList = SqlServerUtil::execToSql($this->SqlServer, $acsql);
    	// 		dd($acList );
    	$arr =[];
    	$ArrData=[];
    	$result=[];
    	$sql = "select FObjectType,FObjectID,FIndex,FAccessMask,FName from gz_ObjectAccessType  ";
    	$data = SqlServerUtil::execTosql($this->SqlServer,$sql);
    	///$acList, $data
    	// 		dd( $menulistData );
    	if($data && $acList){
    		foreach ($data as $k =>$v){
    			foreach ($acList as $k0=>$v0)
    			{
    				if( $v['FObjectType']== $v0['FObjectType']  && $v['FObjectID']== $v0['FObjectID'] ){
    					$temp =[];
    					$temp = explode(',',$v0['Fsqlist']);
    					foreach ($temp as $k1=>$v1)
    					{
    						if($v1 == $v['FAccessMask'] ){
    							$arr[$v['FObjectID']][] = $v;
    						}
    					}
    					
    				}
    			}
    		}
    		// 			dd($menulistData,$arr);
    		//二级
    		foreach ($menulistData as $k3=>$v3)
    		{
    			foreach ($arr as $k4=>&$v4)
    			{
    				//$v3['fobjecttype']== $v4['FObjectType'] &&
    				if( $v3['fobjectid'] == $k4){
    					$menulistData[$k3]['child'] =$v4;
    					
    				}
    			}
    			if(!isset($menulistData[$k3]['child'])){
    				unset($menulistData[$k3]);
    			}
    			
    		}
    		
    		// 			dd($menuTemp,$menulistData );
    		//一级
    		foreach ($menuTemp as $k4=>$v4)
    		{
    			foreach ($menulistData as $k5=>&$v5)
    			{
    				//$v3['fobjecttype']== $v4['FObjectType'] &&
    				if( $v4['fobjecttype'] == $v5['fobjecttype']){
    					$menuTemp[$k4]['children'][] =$v5;
    					
    				}
    			}
    			if(!isset($menuTemp[$k4]['children'])){
    				unset($menuTemp[$k4]);
    			}
    			
    		}
    		
    		//dd( $menuTemp,123 );
    		
    		return $menuTemp ;
    		///if---END
    	}else{
    		return [];
    	}
    	
    }
    
    
    private function logout(Request $request){
        //$request->session()->forget('_token');
    	/* if($request->session()->get('_is_auth')){
    		sqlsrv_query($this->SqlServer, "update gz_admin set last_session =0 where  id='{$request->session()->get('_fuid')}' ");
        } */
        $request->session()->forget('_is_auth');
        //$request->session()->forget('_previous');
//        $request->session()->flush();

//         session(['username'=>null]);
        Session::forget('username');
      
        $is_ret = $request->get('is_ret') ?? 0;
        if($is_ret != 1){
            $this->response['Error']= 2;
            $this->response['Message']= "用户未登录！";
            echo json_encode($this->response);
        }
    }
    //内部web及其它应用接入使用
    public function interRun(Request $request){
        $type = $request->get('type');
        $openAuth = array('logout','setLogin','getAccountingMode','getVersion','postApplyInStockTo');
        $isAuth = in_array($type,$openAuth);
        $username = "";
        if (!$isAuth){
            if (!$request->session()->has('_is_auth')){
                returnData(2, '用户未登录！');
            }else{
                $username = $request->session()->get('_is_auth');
                $FUserID = $request->session()->get('_fuid');
                if(!empty($FUserID)){
                    $request->merge(['FUserID'=> $FUserID]);
                }
            }
        }
        switch ($type){
            case 'getAllCustomerList': //获取所有客户信息集合
				$authinfo = $this->checkaccessright('SYERP','frmMainFlow','201',$username);
				if($authinfo === true){
					$this->getCustomerInfo($request);
				}else{
					returnData(1, $authinfo);
				}               
                break;
            case 'postCustomerTo': //提交触发上传客户信息至华强云仓
                $this->postCustomer($request);
            case 'getAllocationList': //获取调拨单信息列表
                $authinfo = $this->checkaccessright('SYERP','frmMainFlow','41',$username);
                if($authinfo === true){
                    $this->getAllocation($request);
                }else{
                    returnData(1, $authinfo);
                }
                break;
            case 'postApplyInStockTo': //提交触发上传入库申请至华强云仓
                $this->postApplyInStock($request);
                break;
            case 'postApplyOutStockTo': //提交触发上传出库申请至华强云仓
            	$this->postApplyOutStock($request);
            	break;
            case 'postQueryCustomerCreditTo': //查询客户账期信息
                $this->QueryCustomerCredit($request);
                break;
            case 'getVersion': //查询客户账期信息
                $this->getVersion($request);
                break;
            case 'getAccountingMode': //获取账套
                $this->getdb();
                break;
            case 'setLogin': //用户登录
                $this->login($request);
                break;
            case 'logout': //用户登录
                $this->logout($request);
                break;
            default:
                returnData(400, '请求业务参数有误！请查阅接口文档');
                break;
        }
    }
    //对外华强云仓接入使用
    public function openRun(Request $request){
        $type = $request->get('type');
        switch ($type){
            case 'outstock': //出库单推送
                $OrderType = $request->get('OrderType');
                if($OrderType == 1){
                    $this->ycxsddInsert($request);
                }else if($OrderType == 2){
                    $this->ycInStock($request);
                }else{
                    returnData(400, '推送的单据类型');
                }
                break;
            case 'querystock': //库存查询
                $this->ICInventorybal($request);
                break;
            case 'instock': //入库单
                $this->postInstock($request);
                break;
            case 'customerbill': //入库单
            	$this->ycqtckInsert($request);
            	break;
                
            default:
                returnData(400, '请求业务参数有误！请查阅接口文档');
                break;
        }
    }
    //获取所有客户信息集合
    private function getCustomerInfo(Request $request){
        //        $sql="select FName as CustomerName,FAddress as Address,FPhone as Telephone,FMobileNumber as Mobile,FContact as Contact,Femployee as SalesName,FSMSPhoneNumber as CustomerUUID from t_organization";
//        $resCustomer = SqlServerUtil::exec($this->SqlServer, $sql);
//        returnData(0,'Success!',$resCustomer);
    	$this->log(__FUNCTION__,$request);
        $page= $request ->get('page');
        if(!isset($page)) $page =1;
        $limit= $request ->get('limit');
        if(!isset($limit)) $limit =20;
        $pages = ($page-1)* $limit;
        $search ='';
		$FUserID = $request ->get('FUserID');
        if (isset($request->keyword)) {
            if(!empty($request->keyword)){
                $search = "  and (tor.FMobileNumber like '%".$request->keyword."%'  or tor.FName like '%".$request->keyword."%' ) ";
            }
        }
		
		$lefe_join = '';
        $where = '';
		$countWhere = '';
        if(isset($FUserID)){
            $res_sql = $this->AddDataRight('',201,$FUserID,1);
            $lefe_join = isset($res_sql['lefe_join'])?$res_sql['lefe_join']:'';
            $where = isset($res_sql['where'])?$res_sql['where']:'';
			$countWhere = isset($res_sql['countWhere'])?$res_sql['countWhere']:'';
        }
        $sql = "SELECT TOP {$limit} tor.FName as CustomerName,tor.FAddress as Address,tor.FPhone as Telephone,tor.FMobileNumber as Mobile,tor.FContact as Contact,tem.FName as SalesName,tor.FSMSPhoneNumber as CustomerUUID
                FROM t_organization tor
                left join t_emp tem on tem.fitemid=tor.Femployee
                {$lefe_join}
                where tor.FNumber NOT IN (SELECT TOP {$pages}  tor.FNumber FROM t_organization  tor {$lefe_join} where 1=1  {$search} {$where}) and 1=1  {$search} {$where}";

        $sql = iconv('UTF-8', 'GBK', $sql);
        $res = SqlServerUtil::exec($this->SqlServer,$sql);
        $resCustomer = [];
        $countSql ="SELECT COUNT(1) AS total FROM t_organization tor {$lefe_join}  where 1=1 {$search} {$countWhere}";
        $countSql = iconv('UTF-8', 'GBK', $countSql);
        $count = SqlServerUtil::exec($this->SqlServer, $countSql);
        $resCustomer['total'] = $count ? $count[0]['total']:0;
        $resCustomer['size'] = $page;
        $last_page =0;
        if($count && count($count)>0){
            $last_page = ceil($count[0]['total']/$limit);
        }
        $resCustomer['result'] = $res;
        $resCustomer['last_page'] =$last_page;
        returnData(0,'Success!',$resCustomer);
    }
    //页面提交触发上传客户信息
    private function postCustomer(Request $request){
		$this->log(__FUNCTION__,'----1----'.$request);
        if($request->has('CustomerInfo') && $request->CustomerInfo != '' && !empty($request->CustomerInfo)){
			foreach ($request->CustomerInfo as $k => $v){
                if(!isset($v['CustomerName'])||empty($v['CustomerName'])){
                    returnData(1, '您上传的数据中客户名不能为空！');
                }else if(!isset($v['Contact'])||empty($v['Contact'])){
                    returnData(1, '您上传的<'.$v['CustomerName'].'>数据中联系人不能为空！');
                }else if(!isset($v['Mobile'])||empty($v['Mobile'])){
                    returnData(1, '您上传的<'.$v['CustomerName'].'>数据中手机号不能为空！');
                }
            }
            $str = json_encode($request->CustomerInfo);
            $sign = md5($str.'0f2800b8ae164dedb99be3da416f6cf0');
            $res = $this->curlPost("https://yuncang.hqbuy.com/gys/OpenApi/Supplier/SaveCustomer?signature=".$sign,$str);
            $res = json_decode($res,true);
			
            if(isset($res['Error']) && $res['Error'] == 0) {
				
                foreach ($res['Data'] as $k => $v) {
                    $sql = "UPDATE t_Organization SET FSMSPhoneNumber = '{$v['CustomerUUID']}' WHERE FName = '{$v['CustomerName']}' ";
                    $sql = iconv('UTF-8', 'GBK', $sql);
                    SqlServerUtil::execSql($this->SqlServer,$sql);
                }
                returnData(0, '同步成功',$res);
            }else{
                returnData(1, '上传失败');
            }
        }
    }
    //获取调拨单信息列表
    private function getAllocation(Request $request){
        $start= $request ->get('start');
        if(!isset($start)) $start =getCurrentTime(4);
        $start1 =$start;
        $start = $start1.' 00:00:00';
        $end= $request ->get('end');
        if(!isset($end)){ 
        	$end =$start1.' 23:59:59';
        }else{
        	$end = $end.' 23:59:59';
        };
        
        $typeid = $request ->get('typeid')?$request ->get('typeid'):1;
        if($typeid ==1){
        	$sql="select u1.FDate,u1.FInterID,u1.FBillNo,tem.FName,u2.FItemID,u2.Fauxqty,tici.fname as FItemIDName,tici.fnumber as FItemIDNumber,tici.FHelpCode,tstc0.fname as FDCStockIDname
        	from icstockbill u1
        	left join t_emp tem on tem.fitemid=u1.FEmpID
        	left join icstockbillentry u2 on u2.finterid=u1.finterid
        	left join t_icitem tici on tici.fitemid=u2.fitemid
        	left join t_stock tstc0 on tstc0.fitemid=u2.FDCStockID
        	where u1.FTranType = 41 and u1.FBillNoGS ='' and tstc0.fname = '华强云仓' and  u1.FDate >='{$start}' and u1.FDate <='{$end}' order by u1.FBillNo desc";
        	$sql = iconv('UTF-8', 'GBK', $sql);
        	$res = SqlServerUtil::exec($this->SqlServer, $sql);
        	$list = array();
        	if(is_array($res) && count($res)>0){
        		$i = 0;
        		$FBillNo = "";
        		foreach ($res as $k => $v){
        			if($FBillNo != $v['FBillNo']){
        				$i = 0;
        				$FBillNo = $v['FBillNo'];
        			}
        			$list[$v['FBillNo']]['FInterID'] = $v['FInterID'];
        			$list[$v['FBillNo']]['DeliveryCode'] = $v['FBillNo'];
        			$list[$v['FBillNo']]['Remark'] = '';
        			$list[$v['FBillNo']]['SalesName'] = $v['FName'];
        			$list[$v['FBillNo']]['Details'][$i]['MaterialCode'] = $v['FHelpCode'];
        			$list[$v['FBillNo']]['Details'][$i]['Quantity'] = $v['Fauxqty']*1000;
        			$list[$v['FBillNo']]['Details'][$i]['Unit'] = 'PCS';
        			$i++;
        		}
        	}
        	returnData(0,'Success!',$list);
        }else{
        	$sql="select u1.FDate,u1.FInterID,u1.FBillNo,u1.FBillNoGS,u1.FText1,tem.FName,u2.FItemID,u2.Fauxqty,tici.fname as FItemIDName,tici.fnumber as FItemIDNumber,tici.FHelpCode,tstc0.fname as FDCStockIDname
        	from icstockbill u1
        	left join t_emp tem on tem.fitemid=u1.FEmpID
        	left join icstockbillentry u2 on u2.finterid=u1.finterid
        	left join t_icitem tici on tici.fitemid=u2.fitemid
        	left join t_stock tstc0 on tstc0.fitemid=u2.FSCStockID
        	where u1.FTranType = 41 and u1.FBillNoGS ='' and tstc0.fname = '华强云仓' and  u1.FDate >='{$start}' and u1.FDate <='{$end}' order by u1.FBillNo desc";
        }
      //echo $sql;die;
        $sql = iconv('UTF-8', 'GBK', $sql);
        $res = SqlServerUtil::exec($this->SqlServer, $sql);
        $list = array();
        if(is_array($res) && count($res)>0){
            $i = 0;
            $FBillNo = "";
            foreach ($res as $k => $v){
                if($FBillNo != $v['FBillNo']){
                    $i = 0;
                    $FBillNo = $v['FBillNo'];
                }
				$list[$v['FBillNo']]['FInterID'] = $v['FInterID'];
                $list[$v['FBillNo']]['DeliveryCode'] = $v['FBillNo'];
                $list[$v['FBillNo']]['Remark'] = '';
                $list[$v['FBillNo']]['ApplyUser'] = $v['FName']; //申请人
                $list[$v['FBillNo']]['Mobile'] = $v['FText1']; //手机号
                $list[$v['FBillNo']]['Contact'] = $v['FName']; //联系人
                
                $list[$v['FBillNo']]['Details'][$i]['MaterialCode'] = $v['FHelpCode'];
                $list[$v['FBillNo']]['Details'][$i]['Quantity'] = $v['Fauxqty']*1000;
                $list[$v['FBillNo']]['Details'][$i]['Unit'] = 'PCS';
                $i++;
            }
        }
        returnData(0,'Success!',$list);
    }
    //页面提交触发上传入库申请
    private function postApplyInStock(Request $request){
		$this->log(__FUNCTION__,'----1----'.$request);
        $postData['DeliveryCode'] = $request->DeliveryCode;
        $postData['Remark'] = $request->Remark;
        $postData['SalesName'] = $request->SalesName;
        $postData['Details'] = $request->Details;
		$sql="select u1.FEntryID from ICStockBill v1 inner join ICStockBillEntry u1 on v1.FInterID = u1.FInterID inner join t_icitem tic on tic.FItemID = u1.FItemID where v1.FInterID ={$request->FInterID} and tic.FHelpCode =''";
        $sql = iconv('UTF-8', 'GBK', $sql);
        $res = SqlServerUtil::exec($this->SqlServer, $sql,2);

        if(isset($res['FEntryID'])&&!empty($res['FEntryID'])){
            returnData(1,'分录号：'.$res['FEntryID'].'的物料资料中，原厂料号为空',[]);
        }
        //$this->log(__FUNCTION__,__LINE__.'----1----'.$res['FEntryID']);
		
        $str = json_encode($postData);
        $sign = md5($str.'0f2800b8ae164dedb99be3da416f6cf0');
        $res = $this->curlPost("https://yuncang.hqbuy.com/gys/OpenApi/Supplier/ApplyInStock?signature=".$sign,$str);
		$this->log(__FUNCTION__,'----1----'.$res);
        $res = json_decode($res,true);
        if(isset($res['Error']) && $res['Error'] == 0) {
            $sql = "UPDATE icstockbill SET FBillNoGS = '{$res['Data']['InStockNoticeNO']}' WHERE FBillNo = '{$request->DeliveryCode}' ";
            SqlServerUtil::execSql($this->SqlServer,$sql);
        }
		echo json_encode($res);
    }
    //入库单
    private function postInstock(Request $request){
        $type = $request->get('type');
        if ($type != 'instock') {
            returnData(400, '入库单参数不正确');
        }
        if($request->has('DeliveryCode') && $request->DeliveryCode != '' && !empty($request->DeliveryCode)&& $request->has('Details') && $request->Details != '' && !empty($request->Details)){
            //查询库单及明细
            $sql="select u1.FInterID as FID,u1.FBillNo,u2.FItemID,u2.Fauxqty,tici.fname as FItemIDName,tici.fnumber as FItemIDNumber,tici.FHelpCode,u2.FItemID,u2.FInterId,u2.FEntryID from icstockbill u1 left join icstockbillentry u2 on u2.finterid=u1.finterid left join t_icitem tici on tici.fitemid=u2.fitemid  where u1.FTranType = 41 and u1.FBillNo = '{$request->DeliveryCode}' order by u1.FBillNo ";
            $res = SqlServerUtil::exec($this->SqlServer, $sql);
            $tlist = [];
            foreach ($res as $k => $v) {
                if(isset($tlist[$v['FHelpCode']]['Quantity'])){
                    $tlist[$v['FHelpCode']]['Quantity'] += $v['Fauxqty'];
                }else{
                    $tlist[$v['FHelpCode']]['Quantity'] = $v['Fauxqty'];
                }
                $tlist[$v['FHelpCode']]['FHelpCode'] = $v['FHelpCode'];
                $tlist[$v['FHelpCode']]['FInterId'] = $v['FInterId'];
                $tlist[$v['FHelpCode']]['FEntryID'][] = $v['FEntryID'];
            }
            foreach ($request->Details as $k => $v) {
                $Msg = "";
                if($tlist[$v['MaterialCode']]['Quantity'] == $v['Quantity']){
                    $Msg = "验货成功";
                }else{
                    $Quantity = 0;
                    if($tlist[$v['MaterialCode']]['Quantity'] > $v['Quantity']){
                        $Quantity = $tlist[$v['MaterialCode']]['Quantity'] - $v['Quantity'];
                        $Msg = "验货数量有误缺少：".$Quantity;
                    }else{
                        $Quantity = $v['Quantity'] - $tlist[$v['MaterialCode']]['Quantity'];
                        $Msg = "验货数量有误多出：".$Quantity;
                    }

                }
                $FEntryIDs = implode(',',$tlist[$v['MaterialCode']]['FEntryID']);
                $sql = "UPDATE ICStockBillEntry SET 1 = '{$Msg}' WHERE FInterId = {$tlist[$v['MaterialCode']]['FInterId']} and FEntryID in ({$FEntryIDs})";
                $sql = iconv('UTF-8', 'GBK', $sql);
                SqlServerUtil::execSql($this->SqlServer,$sql);
            }
        }
    }
    
    /**
    * 聚一科技 ^_^
    * 出库单申请 提交 
    * @date: 2020年7月27日
    * @author: lq
    * @version:App V2.0
    */
    private function postApplyOutStock(Request $request){
    	$this->log(__FUNCTION__,'----1----'.$request);
    	$DeliveryCode = $request->DeliveryCode;//单号
    	
    	$postData['ApplyUser'] = $request->ApplyUser; //申请人
    	$postData['Contact'] = $request->Contact; //联系人
    	$postData['Mobile'] = $request->Mobile; //提货人手机号
    	
    	$postData['Remark'] = $request->Remark;
    	$postData['Details'] = $request->Details;
    	 $sql="select u1.FEntryID from ICStockBill v1 inner join ICStockBillEntry u1 on v1.FInterID = u1.FInterID inner join t_icitem tic on tic.FItemID = u1.FItemID where v1.FInterID ={$request->FInterID} and tic.FHelpCode =''";
    	$sql = iconv('UTF-8', 'GBK', $sql);
    	$res = SqlServerUtil::exec($this->SqlServer, $sql,2);
    	
    	if(isset($res['FEntryID'])&&!empty($res['FEntryID'])){
    		returnData(1,'分录号：'.$res['FEntryID'].'的物料资料中，原厂料号为空',[]);
    	}
    	$FEntryID =isset($res['FEntryID'])?$res['FEntryID']:'';
    	$this->log(__FUNCTION__,__LINE__.'----1----'.$FEntryID);
    	$str = json_encode($postData);
    	$sign = md5($str.'0f2800b8ae164dedb99be3da416f6cf0');
    	$res = $this->curlPost("https://yuncang.hqbuy.com/gys/OpenApi/Supplier/ApplyOutStock?signature=".$sign,$str);
    	$this->log(__FUNCTION__,'----1----'.$res);
    	$res = json_decode($res,true);
    	if(isset($res['Error']) && $res['Error'] == 0) {
    		$sql = "UPDATE icstockbill SET FBillNoGS = '{$res['Data']['OrderNO']}' WHERE FBillNo = '{$DeliveryCode}' ";
    		SqlServerUtil::execSql($this->SqlServer,$sql);
    	}
    	echo json_encode($res);
    }
    
    
    //查询客户账期信息
    private function QueryCustomerCredit(Request $request){
        $postData['CustomerUUID'] = $request->CustomerUUID;
        $str = json_encode($postData);
		$this->log(__FUNCTION__,__line__.'----1----'.$str);
        $sign = md5($str.'0f2800b8ae164dedb99be3da416f6cf');
        $res = $this->curlPost("https://yuncang.hqbuy.com/gys/OpenApi/Supplier/QueryCustomerCredit?signature=".$sign,$str);
		$this->log(__FUNCTION__,'----1----'.$res);
        $res = json_decode($res,true);
        if(isset($res['Error']) && $res['Error'] == 0) {
            $sql = "UPDATE t_Organization SET FlastTradeAmount = '{$res['Data']['MaxCredit']}',
                    FlastRPAmount = '{$res['Data']['AvailableCredit']}',
                    FmaxDealAmount = '{$res['Data']['UsedCredit']}'
                    FdebtLevel = '{$res['Data']['Status']}'
                    FCarryingAOS = '{$res['Data']['UsedCredit']}'
                    WHERE FSMSPhoneNumber = '{$request->CustomerUUID}' ";
			$this->log(__FUNCTION__,'----1----'.$sql);
            SqlServerUtil::execSql($this->SqlServer,$sql);
			returnData(0, '同步成功',$res);
        }
		returnData(1, '上传失败');
    }
    //模拟POST提交
    private function curlPost($url, $data,$showError=1){
        $ch = curl_init();
        $header = ['auth:'.'f844b72e956247868f6be6a4de444e58','content-type:application/json'];
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch))
        {
            echo 'Errno' . curl_error($ch); //捕抓异常
        }
        curl_close($ch); // 关闭CURL会话
        return $tmpInfo; // 返回数据
    }
    //往来收款
    private function receipt(Request $request,$is_FTaxRate = 0){
		$this->log(__FUNCTION__,'----1----'.$request);
        //起始日期
//		$startDate = $request->input('startDate');
        //截至日期
//		$endDate = $request->input('endDate');
        //往来客户代码
//		$customerCode = $request->input('customerCode');
        //往来客户名称
        $customerName = $request->input('customerName');
        $customerName = iconv('UTF-8', 'GBK', $customerName);
        //收款帐户名称
        $accountName = $request->input('accountName') ?? '支付宝';
        $accountName = iconv('UTF-8', 'GBK', $accountName);
        //单据编号(如果为空就是该用户下的所有订单)
        $billno = $request->input('billNo');
        $tSql = "";
        if(!empty($billno)){
            if(empty($tSql)){
                $tSql = " and v1.fbillno='".$billno."'";
            }else{
                $tSql .= " and v1.fbillno='".$billno."'";
            }
        }
        if(!empty($customerName)){
            if(empty($tSql)){
                $tSql = " and ttr.fname='".$customerName."'";
            }else{
                $tSql .= " and ttr.fname='".$customerName."'";
            }
        }
        //获取往来收款单源销售出库订单信息和客户信息 and  v1.fdate >='".$startDate."' and v1.fdate <='".$endDate."'
        $sql="select v1.FDeptID,v1.FEmpID,v1.FText1,v1.FText2,v1.FText3,v1.Fexplanation,ttr.fname as ftranname,ttr.FNumber as ftrannumber,ttr.FItemID as ftranId,v1.ftrantype,v1.fbillno,v1.fbillnogs,v1.fsourcebillno as fbillnodd,v1.finterid,v1.fdate,tcur.fcurrencyid as FBillCurrencyID,tcur.fname as FBillCurrencyIDName,v1.fexchangerate as fentryexchangerate,v1.fbillsumamount as fbillamount,v1.FYJSAmount,v1.fbillsumamount-isnull(v1.FYJSAmount,0) as FWJSAmount,v1.fbillsumamount-isnull(v1.FYJSAmount,0) as FSJSAmount
		,tdp.fname as fdeptidname,tem.fname as fempidname,u1.FCustOrderNo,u1.FAuxName1,u1.fskph,se.FBillNoGS as fbillnogsdd,v1.FDateJS as FBillDateJS
		,tse.FName as FSettleIDName,ttr.FShortName as ftranshortname,u1.FDZBZ,u1.fdzrq,u1.FTaxRate,u1.FUPC
		from icstockbill v1 left join t_organization ttr on ttr.fitemid=v1.fsupplyid 
		left join ICStockBillEntry u1 on v1.FInterID=u1.FInterID and u1.FEntryID =1
		left join SEOrder se on se.FInterID = u1.FOrderInterID 
		left join t_currency tcur on tcur.fcurrencyid=v1.fcurrencyid
		left join t_department tdp on tdp.fitemid=v1.fdeptid
		left join t_emp tem on tem.fitemid=v1.fempid
		left join t_Settle tse on tse.FItemID = v1.FSettleID
		where v1.ftrantype=21 and v1.fcancellation=0 ".$tSql." and 2=2 and abs(v1.fbillsumamount)-abs(isnull(v1.FYJSAmount,0))>0
		order by v1.fdate,v1.fbillno";
        $customerOrder = SqlServerUtil::exec($this->SqlServer, $sql);
        $resOrder = array();
        if(is_array($customerOrder) && count($customerOrder)>0){
            foreach ($customerOrder as $k => $v){
                $resOrder = $v;
            }
        }
        //获取收款帐户1
        $t_account = SqlServerUtil::exec($this->SqlServer, "select a.faccountid,a.Fnumber,a.FFullName as Fname,a.FName from t_account a where 1=1 and 2=2 and a.fdelete=0 and a.FName = '".$accountName."' order by a.FNumber ", 2);
        if(!isset($t_account['faccountid'])||empty($t_account['faccountid'])){
            //$t_account = SqlServerUtil::exec($this->SqlServer, "select top 1 faccountid from t_Account where FDetail =1 and FIsCash =1 order by FNumber ", 2);
			//20200602卢婷要求
            //所有客户的单只要是未税的进入到往来收款的都可以为现金
			if($is_FTaxRate == 0){
                $sql = "select top 1 faccountid from t_Account where FName='现金' order by FNumber ";
                $sql = iconv('UTF-8', 'GBK', $sql);
                $t_account = SqlServerUtil::exec($this->SqlServer, $sql,2);
            }else{
                $sql = "select top 1 faccountid from t_Account where FName='华强代收' order by FNumber ";
                $sql = iconv('UTF-8', 'GBK', $sql);
                $t_account = SqlServerUtil::exec($this->SqlServer, $sql,2);
            }
        }
        //获取客户
        DB::beginTransaction();
        //获取收款单据编号
        $retICMaxNum = SqlServerUtil::exec($this->SqlServer, "select * from ICMaxNum where FTableName ='t_rp_rbill' ", 2);
        $FBillID = 0;
        $seoUP = 0;
        if ($retICMaxNum) {
            $FBillID = $retICMaxNum['FMaxNum'] + 1;
            $seoUP = DB::table('ICMaxNum')->where('FTableName', 't_rp_rbill')->update(['FMaxNum' => $FBillID]);
        }
        //获取系统单号
        $FBillNo=$this->getFBillNo("1000201");
		//处理付款日期时间
        $dTime = getCurrentTime(1);
        //整理收款单据表数据
        $Receipt = [
            'FBillID'=>$FBillID,
            'FClassTypeID'=>1000201,
            'FYear'=>0,
            'FPeriod'=>0,
            'FDate'=>date('Y-m-d',time()),
            'FReceiveTypeId'=>'1001',
            'FCurrencyID'=>1,
            'FSubSystemID'=>'',
            'FExchangeRate'=>1,
            'FSettleId'=>0,
            'FSettleIdNo'=>'',
            'FExplanation'=>'',
            'FAmountFor'=>$resOrder['fbillamount'],
            'FAmount'=>$resOrder['fbillamount'],
            'FReceiveAmountFor'=>$resOrder['fbillamount'],
            'FReceiveAmount'=>0,
            'FDiscount'=>1,
            'FDiscountDsp'=>100,
            'FDiscountAcctId'=>0,
            'FDiscountAmount'=>0,
            'FDiscountAmountFor'=>0,
            'FRP'=>0,
            'FManagerId'=>0,
            'FDepartmentId'=>$resOrder['FDeptID'],//20200526添加映射出库单的部门
            'FEmployeeId'=>$resOrder['FEmpID'], //20200526添加映射出库单的业务员
            'FCustomerID'=>$resOrder['ftranId'],
            'FStatus'=>0,
            'FBillNo'=>$FBillNo,
            'FROB'=>'1',
            'FRedFlag'=>'',
            'FCheckAmount'=>0,
            'FCheckAmountFor'=>0,
            'FVoucherId'=>0,
            'FCheckStatus'=>0,
            'FAcctId'=>$t_account['faccountid'],
            'FMultiCheckLevel1'=>0,
            'FMultiCheckLevel2'=>0,
            'FFeeCurID'=>0,
            'FFee2AcctId'=>0,
            'FFee2'=>0,
            'FFee3AcctId'=>0,
            'FFee3'=>0,
            'FTime'=>$dTime,
            'FFeeAcctId'=>0,
            'FFee'=>0,
            'FYJSAmount'=>$resOrder['fbillamount'],
            'FBillerID'=>16394
        ];
        //整理收款单据明细数据
        $ReceiptDetails = [
            'FBillID'=>$FBillID,
            'FInterId'=>$resOrder['finterid'],
            'FBillNo'=>$resOrder['fbillno'],
            'FBillAmountFor'=>$resOrder['fbillamount'],
            'FBillAmount'=>0,
            'FBillReceiveAmountFor'=>0,
            'FBillReceiveAmount'=>0,
            'FBillSettleAmountFor'=>$resOrder['fbillamount'],
            'FBillSettleAmount'=>$resOrder['fbillamount'],
            'FBillNote'=>'',
            'FID_SRC'=>0,
            'FClassID_SRC'=>21,
            'FBillCurrencyID'=>1,
            'FBillUnReceiveAmountFor'=>0,
            'FBillUnReceiveAmount'=>0,
            'FEntryExchangeRate'=>1,
            'FBillDate'=>date('Y-m-d',time()),
            'FIndex'=>1,
            'FUPC'=>'',
            'FBillNoGSDD'=>'',
            'FSKPH'=>'',
            'FAuxName1'=>'',
            'FBillNoDD'=>'',
            'FBillNoGS'=>'',
            'FPreBL'=>0,
            'FCustOrderNo'=>'',
            'FEntryIDSrc'=>0
        ];
        $retReceipt = DB::table('t_rp_rbill')->insert($Receipt);
        $retReceiptDetails = DB::table('t_rp_rbillentry')->insert($ReceiptDetails);
        if ($retReceipt && $retReceiptDetails && $seoUP) {
            DB::commit();
//            returnData('200', '成功', ['fbillno' => $FBillNo]);
			$sql = "UPDATE icstockbill SET FJSRQ = '{$dTime}',
                    FYJSAmount = '{$resOrder['fbillamount']}'
                    WHERE FBillNo = '{$billno}' ";
            SqlServerUtil::execSql($this->SqlServer,$sql);
          //  return true;
        } else {
            DB::rollback();
//            returnData('400', '失败');
            //return false;
        }
    }
    //出库单推送
    private function ycxsddInsert(Request $request)
    {
    	//dd(123);
        $this->log(__FUNCTION__,'----1----'.$request);
        $type = $request->get('type');
        if ($type != 'outstock') {
            returnData(400, '出库单参数不正确');
        }
        //这里默认客户 ---华强云仓
        //单据类型 1-销售订单 2-调拨出库
//        $OrderType = $request->get('OrderType');
//        if ($OrderType != 1 || $OrderType != 2) {
//            returnData('400', '单据类型不正确');
//        }

        //获取客户
//        $fcutomerName = $request->get('fcutomername') ?? '华强云仓';
        $CompanyName  = $request->get('CompanyName') ?? '华强云仓';
		//处理公司名是《现金客户-》开始的数据为该条件成立触发往来收款单 20200602卢婷要求
        //类似SO2006011617030950这个单的客户栏归属《现金客户-张志强》（因为没有这个客户，所以我们默认为-华强云仓）
        //或结算方式为现金的（这个结算方式为现金：是根据该客户信息预设的结算方式），
        //满足《现金客户-》该条件的都进入往来收款
        $arrCompanyName = explode('-',$CompanyName)[0];
        if($arrCompanyName != '现金客户'){
            $arrCompanyName = '';
        }
        $PayName = $request->get('PayName') ?? '挂账';
        $Delivery = $request->get('Delivery') ?? '送货';
        $Mobile = $request->get('Mobile');
        $Contact = $request->get('Contact');
        $AccountUUID = $request->get('AccountUUID');
        $AccountMobile = $request->get('AccountMobile');
        $CustomerUUID = $request->get('CustomerUUID');
//        $saleidname = $request->get('SaleidName') ?? "现销";
//        $settlementidname = $request->get('settlementidname') ?? "现金";
//        $deliveryidname = $request->get('deliveryidname') ?? "送货";
//        $fcurrencyidname = $request->get('fcurrencyidname') ?? "人民币";
//        $stocknameidname = $request->get('stocknameidname') ?? "深圳仓";
        $FBillNoGS = $request->get('OrderNO');
        //OrderType --1 销售订单，，2--调拨出库
        if (empty($FBillNoGS)) {
            returnData(400, '单据号不能为空');
        }
        $OrderType = $request->get('OrderType');
        if (!in_array($OrderType, [1])) {
            returnData(400, '单据类型不正确');
        }
        //TradingMode 交易方式 0-无 1-华强代售 2-商家自营
        $TradingMode = $request->get('TradingMode');
        $PayTime = $request->get('PayTime');
        $pagam = $request->all();
        $patten = "/^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/";
        if (!preg_match($patten, $PayTime)) {
            returnData(400, '销售订单时间格式不正确');
        }

        $OrderType = 2;

        $fbillnoxmArr = SqlServerUtil::exec($this->SqlServer, "SELECT v1.finterid,v1.fbillno,v1.FBillNoGS FROM ICStockBill v1 WHERE v1.FBillNoGS = '{$FBillNoGS}'", 2);
        if ($fbillnoxmArr) {
            returnData(400, '单据单号已存在！ ');
        }

        $Time = $request->get('Time');
        if (!preg_match($patten, $Time)) {
            returnData(400, '制单时间格式不正确');
        }
        //税率
        $fdiscountrate = 0;

        $json = $request->get('Details');
        //$entryData = json_decode($json,true);
        $entryData = $json;
        if (is_array($entryData) && count($entryData) > 0) {
            $sql="select FItemID from t_stock where FName = '华强云仓'";
            $sql = iconv('UTF-8', 'GBK', $sql);
            $res_stock = SqlServerUtil::exec($this->SqlServer, $sql,2);
            //[{"MaterialCode":"76","Quantity":"100","Price":"1.19"},{"fnumber_wl":"1127","fqty":"50","fprice":"10.8"}]
            $entry_wl = array_column($entryData, 'MaterialCode');
            $where_wl = '';
            foreach ($entry_wl as $k => $ewl) {
//                $sql = "select tme.FName as funitidname,a.FParentID,a.fitemid,a.fnumber,a.fname,a.funitid,a.fmodel,a.fhelpcode,a.fnote,a.FAlias,a.fsaleprice,a.Fdefaultloc,tst.fname as fdefaultlocname from t_icitem a
//    			left join t_stock tst on tst.fitemid=a.fdefaultloc
//    			LEFT JOIN t_measureunit tme on a.funitid=tme.fmeasureunitid
//    			where 1=1 and a.FNumber= '{$ewl}' and a.fdeleted=0 ";
                $sql = "select tme.FName as funitidname,a.FParentID,a.fitemid,a.fnumber,a.fname,a.funitid,a.fmodel,a.fhelpcode,a.fnote,a.FAlias,a.fsaleprice,a.Fdefaultloc,tst.fname as fdefaultlocname from t_icitem a
    			left join t_stock tst on tst.fitemid=a.fdefaultloc
    			LEFT JOIN t_measureunit tme on a.funitid=tme.fmeasureunitid
    			where 1=1 and a.FHelpCode= '{$ewl}' and a.fdeleted=0 ";
                $wuliao = SqlServerUtil::exec($this->SqlServer, $sql, 2);
                if (empty($wuliao)) {
                    returnData(400, '物料代号不正确');
                    break;
                }
                $entryData[$k]['fnumber_wl'] = $wuliao['fitemid'];
                $entryData[$k]['fstockid'] = $res_stock['FItemID'];
                //$entryData[$k]['funitid'] = empty($danwei) ? 69 : $wuliao['funitid'];
                $entryData[$k]['funitid'] = $wuliao['funitid'];
            }
            //判断数量
            $totalmoney=0;
            foreach ($entryData as $k => $v) {
                if (!isIntNum($v['Quantity'])) {
                    returnData(400, '数量不为空 或格式不正确');
                    break;
                }
                if (!isFloatNum($v['Price'])) {
                    returnData(400, '单价不为空 或格式不正确');
                    break;
                }
                $entryData[$k]['fqty'] = $v['Quantity'];
                $entryData[$k]['fprice'] = $v['Price'];

                $totalmoney +=$v['Quantity']*$v['Price'];

            }
        } else {
            returnData(400, '参数错误');
        }
        //获取配送方式标示ID
        $sqlStr = iconv('UTF-8', 'GBK', "SELECT FInterID,FName  FROM t_submessage WHERE  ftypeid in (32) and fdeleted=0 and FName = '".$Delivery."'");
        $FFetchStyle = SqlServerUtil::exec($this->SqlServer,$sqlStr,2 );
        //处理客户信息
        //======================================================处理客户信息start============================================================
        $fcutomerName = iconv('UTF-8', 'GBK', $CompanyName);
        //判断客户 select FItemID as customerid,FStatus,FName,FNumber,FAddress,FCity,FProvince,FCountry,FPhone,FEmail,fsetid,FValueAddRate,FxmNumber from t_organization
        $customer = SqlServerUtil::exec($this->SqlServer, "select fnumber,FItemID,FName,FAddress,FPhone,FMobileNumber,FContact,FSetID,FSaleID,Femployee,Fdepartment,FcurrencyID,FValueAddRate from t_organization where Fname='{$fcutomerName}' ", 2);
		//解决非挂账客户栏归属华强云仓20200602卢婷要求
        //类似SO2006011742103547这个单的客户栏归属《华强云仓》条件是非挂账的
        if($PayName != '挂账'){
            $customer = '';
        }
        if (empty($customer)) {
//            returnData(400, 'ERP客户不正确');
            $fcutomerName = iconv('UTF-8', 'GBK', "华强云仓");
            $customer = SqlServerUtil::exec($this->SqlServer, "select fnumber,FItemID,FName,FAddress,FPhone,FMobileNumber,FContact,FSetID,FSaleID,Femployee,Fdepartment,FcurrencyID,FValueAddRate from t_organization where Fname='{$fcutomerName}' ", 2);
        }

        $customerid = $customer['FItemID'];

        //联系人
        if(empty($Contact)){
            $flxr = $customer['FContact'];
            if ($request->has('flxr') and $request->flxr != '' && !empty($request->flxr)) {
                $flxr = $request->flxr;
            }
        }else{
            $flxr = $Contact;
        }
        //客户联系电话
        if(empty($Mobile)){
            $flxrdh = $customer['FMobileNumber'];
            if ($request->has('flxrdh') and $request->flxrdh != '' && !empty($request->flxrdh)) {
                $flxrdh = $request->flxrdh??$customer['FPhone'];
            }
        }else{
            $flxrdh = $Mobile;
        }

        //地址
        $ffetchadd = $customer['FAddress'];
        if ($request->has('ffetchadd') and $request->ffetchadd != '' && !empty($request->ffetchadd)) {
            $ffetchadd = $request->ffetchadd;
        }
        $Salesid = $customer['FSaleID'];
        $fempid = $customer['Femployee'];
        $fdeptid = $customer['Fdepartment'];
        $Fcurrencyid = $customer['FcurrencyID'];
        $Settlementid = $customer['FSetID'];
        //======================================================处理客户信息end============================================================
        //登录账户 -- 默认manager
        $FUserID = 16394;

        $FExchangeRate = $request->get('fexchangerate') ?? 1;
        if (empty($FExchangeRate)) {
            $FExchangeRate = 1;
        }

        /* //仓库名称
         if($request->has('stocknameid') and $request->stocknameid != '' && !empty($request->stocknameid)){
         $Stock = SqlServerUtil::exec($this->SqlServer, "select fitemid,fnumber,fname from t_stock where fname='{$Stocknameid}'",2);

         if(empty($Stock)){
         returnData('400','仓库设置不正确');
         }
         $Stocknameid = $Stock['fitemid'];
         }else{
         $Stocknameid =70; //默认 70----0001--深圳仓
         } */

        //业务员
        if ($request->has('SalesName') and $request->SalesName != '' && !empty($request->SalesName)) {
            $Femployeestr = iconv('UTF-8', 'GBK', $request->SalesName);
            $FemployeeName = SqlServerUtil::exec($this->SqlServer, "select FItemID,FName from t_emp where fitemid>0 and FName ='{$Femployeestr}'", 2);
            if (empty($FemployeeName)) {
                returnData(400, '销售员不正确');
            }
            $fempid = $FemployeeName['FItemID'];
        }
        //制单员fbilleridname
        //处理指定制单员过程
        $fbillerid = 0;
        $res_user = SqlServerUtil::exec($this->SqlServer, "select fvalue from t_SystemProfile where FKey ='FHQYCGenBillUser'", 2);
        if ($res_user) {
            $sql = "select FUserID,FName from  t_user where FUserID>0 and FName ='{$res_user['fvalue']}'";
            $sql = iconv('UTF-8', 'GBK', $sql);
            $FFName = SqlServerUtil::exec($this->SqlServer, $sql, 2);
            $fbillerid = isset($FFName['FUserID']) ? $FFName['FUserID'] : 16394;
        }else{
            $FFName = SqlServerUtil::exec($this->SqlServer, "select FUserID,FName from  t_user where FUserID>0 and FName ='manager'", 2);
            $fbillerid = isset($FFName['FUserID']) ? $FFName['FUserID'] : 16394;
        }
        //处理含税/未税

        $res_FText = SqlServerUtil::exec($this->SqlServer, "select fvalue from t_SystemProfile where FKey ='FSaleOutTaxFlagFld'", 2);
        $FTaxRate = 0;
        $Fdiscountrate=0;
        if ($res_FText) {
            if($TradingMode == 1){
                //含税
                $FTaxRate = 13;
            }else{
                //未税
                $FTaxRate = 0;
            }
        }
        //审核员fcheckeridname
        $fcheckerid = 16394;
        if ($request->has('fcheckeridname') and $request->fcheckeridname != '' && !empty($request->fcheckeridname)) {
            $FcheckeridnameStr = iconv('UTF-8', 'GBK', $request->fcheckeridname);
            $FcheckeridName = SqlServerUtil::exec($this->SqlServer, "select FUserID,FName from  t_user where FUserID>0 and FName ='{$FcheckeridnameStr}'", 2);
            if ($FcheckeridName) {
                $fcheckerid = $FcheckeridName['FUserID'];
            }
        }
        $fstockid = 0;

        //获取出库标示ID
        $sqlStr = iconv('UTF-8', 'GBK', "select finterid from t_submessage where ftypeid=38 and fdeleted=0 and FName = '华强出库' order by fid ");
        $FBillTypeID = SqlServerUtil::exec($this->SqlServer,$sqlStr,2 );
        DB::beginTransaction();
        //SEOrder--内码id
        $finterid = 1127;
        $SEOrder = SqlServerUtil::exec($this->SqlServer, "select * from ICMaxNum where FTableName ='ICStockBill' ", 2);
        if ($SEOrder) {
            $finterid = $SEOrder['FMaxNum'] + 1;
            $seoUP = DB::table('ICMaxNum')->where('FTableName', 'ICStockBill')->update(['FMaxNum' => $finterid]);
        }
        //获取内码id
        $FBillNo = $this->getFBillNo(21);
		//记录原数据集合写入摘要
        $tFExplanation = '公司名:'.$CompanyName.'==付款方式:'.$PayName;
		$FBillSumAmount = 0;
        $seorderData=[
            'FBrNo' => '',
            'FInterID' => $finterid,
            'FTranType' => 21,
            'FDate' => !empty($PayTime) ? date('Y-m-d', strtotime($PayTime)) : getCurrentTime(4), //交货日期
            'FBillNo' => $FBillNo,

            'FDeptID' => $fdeptid,
            'FEmpID' => $fempid,
            'FCurrencyID' => $Fcurrencyid ?? 1,
            'FSupplyID' => $customerid,
			'FExplanation'=>$tFExplanation,
            'FFetchAdd' => emptyStr($ffetchadd),
            'FSaleStyle' => $Salesid,
            'FBillerID' => $fbillerid,
            'FFManagerID' => 0,
            'FSettleID' => $Settlementid,
            'FExchangeRate' => $FExchangeRate,//汇率
            'FStatus' => 0, //审核
            'FMultiCheckLevel1' => 0,
            'FMultiCheckLevel2' => 0,
            'FMultiCheckDate4' => getCurrentTime(4),
            'FCurCheckLevel' => 0,
            'FRelateBrID' => 0,
            'FImport' => 0,
            'FTranStatus' => 0,
            'FSystemType' => 0,
            'FSelTranType' => 0,
            'FChildren' => 0,
            'FBrID' => 0,
            'FHookStatus' => 0,
            'fposname' => '',
            'FLXR' => emptyStr($flxr),
            'FLXRDH' => emptyStr($flxrdh),
            'FTime' => $Time,
            'FTaxRateH' => $FTaxRate, //税率
            'FEditor' => '',
            'FBillNoGS' => emptyStr($FBillNoGS),
            'FCheckerId' => 0,
            'FDateJS' => getCurrentTime(4),
            'FBillSumAmount' => $totalmoney,
            //'FCheckerId' => $fbillerid,
            //'FCheckDate' => '',
            'FFetchStyle'=>$FFetchStyle['FInterID'],
            'FBillTypeID' =>$FBillTypeID['finterid'],
            'FText1'    => $AccountUUID,
            'FText2'    => $AccountMobile,
            'FText3'    => $CustomerUUID
        ];
        if($TradingMode == 1){
            //含税
            $seorderData[$res_FText['fvalue']] =  '含税';
        }else{
            //未税
            $seorderData[$res_FText['fvalue']] =  '未税';
        }
        $seorderentryData = [];
        foreach ($entryData as $k => $v) {
            //物料id  ---BOM
            $sql = "select icb.FInterID as FBOMInterID,icb.FBOMNumber from t_icitem tic inner join icbom icb on tic.FDefaultWorkTypeID=icb.finterid where tic.FItemID ='{$v['fnumber_wl']}'";
            $bom = SqlServerUtil::exec($this->SqlServer, $sql, 2);
            $FBomInterID = 0;
            $FBOMNumber = '';
            if (!empty($bom)) {
                $FBomInterID = $bom['FBOMInterID'];
                $FBOMNumber = emptyStr($bom['FBOMNumber']);
            }

            $FTaxAmount = 0; //税额
            $FAuxTaxPrice = $v['fprice'];//含税单价
//
//                $FPriceWB = $v['fprice'];
//
//                if ($FExchangeRate != 1) {
//                    $FAmountWB = $v['fqty'] * $FPriceWB;
//                    $FAuxTaxPrice = number_format($FPriceWB * $FExchangeRate, 4, '.', '');
//                }
            $FCalTypeID = 1;
            $FAuxTaxPrice = $FAuxTaxPrice * 1000;
            $fqty = $v['fqty'] / 1000;
            //number_format($num, 2,'.',''); //10.46
            //注意前提：先设置 $FAuxqty、$FAuxTaxPrice、$FTaxRate、$Fdiscountrate
            //通过含税单价计算不含税单价
            $FConsignPrice = number_format($FAuxTaxPrice * ((100 - $Fdiscountrate) / 100), 4, '.', '');
            $FDiscountPrice = number_format($FConsignPrice / (1 + $FTaxRate / 100), 4, '.', '');
            $FAuxPriceNoTax = number_format($FDiscountPrice / ((100 - $Fdiscountrate) / 100), 4, '.', '');
            $FConsignAmount = number_format($fqty * $FConsignPrice, 2, '.', '');
			$FBillSumAmount = $FBillSumAmount + $FConsignAmount;
            $FTaxAmount = number_format($FConsignAmount / (1 + $FTaxRate / 100) * ($FTaxRate / 100), 2, '.', '');
            $FAmountNoTax = number_format($FConsignAmount - $FTaxAmount, 2, '.', '');
            $seorderentryData[$k]['FBrNO'] = '';
            $seorderentryData[$k]['FInterID'] = $finterid;
            $seorderentryData[$k]['FEntryID'] = $k + 1;
            $seorderentryData[$k]['FItemID'] = $v['fnumber_wl'];
            $seorderentryData[$k]['FQty'] = $fqty;
            $seorderentryData[$k]['FAuxQty'] = $fqty; //实发数量
//                $seorderentryData[$k]['FPrice'] = $FAuxPrice; //没有查到 20200519注释

            $seorderentryData[$k]['FTaxRate'] = $FTaxRate;
            $seorderentryData[$k]['FTaxAmount'] = $FTaxAmount;
            $seorderentryData[$k]['FNote'] = '';
            $seorderentryData[$k]['FUnitID'] = $v['funitid'];
            $seorderentryData[$k]['FAuxCommitQty'] = 0;
//                $seorderentryData[$k]['FAuxPrice'] = $FAuxPrice; //成本单价 20200519注释


            $seorderentryData[$k]['FConsignPrice'] = $FConsignPrice; //折后含税单价
            $seorderentryData[$k]['FConsignAmount'] = $FConsignAmount;
            $seorderentryData[$k]['FUnitCost'] = $FConsignAmount;
            $seorderentryData[$k]['FAuxPriceNoTax'] = $FAuxPriceNoTax; //不含税单价
            $seorderentryData[$k]['FAmountNoTax'] = $FAmountNoTax;
            $seorderentryData[$k]['FAmount'] = 0;


            $seorderentryData[$k]['FSourceEntryID'] = 0;
            $seorderentryData[$k]['FBatchNo'] = '';
            $seorderentryData[$k]['FBomInterID'] = $FBomInterID;
            $seorderentryData[$k]['FMapNumber'] = '';
            $seorderentryData[$k]['FMapName'] = '';
            $seorderentryData[$k]['FAuxPropID'] = 0;
            $seorderentryData[$k]['FAuxTaxPrice'] = $FAuxTaxPrice; //含税单价

            $seorderentryData[$k]['FSourceTranType'] = 0;
            $seorderentryData[$k]['FSourceInterId'] = 0;
            $seorderentryData[$k]['FSourceBillNo'] = '';
            $seorderentryData[$k]['FContractInterID'] = 0;
            $seorderentryData[$k]['FContractBillNo'] = '';
            $seorderentryData[$k]['FFee'] = 0;
            $seorderentryData[$k]['FFeeHK'] = 0;
            $seorderentryData[$k]['FKFPeriod'] = 0;
            $seorderentryData[$k]['FEntryNum1'] = 0;
            $seorderentryData[$k]['FSKPH'] = '';

            $seorderentryData[$k]['FDCStockID'] = $v['fstockid'];
            $seorderentryData[$k]['FCalTypeID'] = 1;
            $seorderentryData[$k]['FCostOBJID'] = 0;
            $seorderentryData[$k]['FCostObjGroupID'] = 0;
            $seorderentryData[$k]['FAuxQtyMust'] = 0;
            $seorderentryData[$k]['FAuxPriceRef'] = 0;
            $seorderentryData[$k]['fbakqty'] = 0;

            $seorderentryData[$k]['FDiscountPrice'] = $FDiscountPrice;
            $seorderentryData[$k]['FCustItemModel'] = '';
            $seorderentryData[$k]['FXLH'] = '';
            $seorderentryData[$k]['FUPC'] = '';
            $seorderentryData[$k]['FEntryText1'] = '';
            $seorderentryData[$k]['FEntryText2'] = '';
            $seorderentryData[$k]['FEntryText3'] = '';

            $seorderentryData[$k]['FBOSUnitID'] = 0;
            $seorderentryData[$k]['FBOSQty'] = 0;
            $seorderentryData[$k]['fbosqtyrest'] = 0;
            $seorderentryData[$k]['FBOSCoe'] = 0;
            $seorderentryData[$k]['FBOSPrice'] = 0;
            $seorderentryData[$k]['FGrossWeight'] = 0;
            $seorderentryData[$k]['FTotalWeight'] = 0;
            $seorderentryData[$k]['FSize'] = 0;
            $seorderentryData[$k]['FTotalSize'] = 0;

            $seorderentryData[$k]['FAuxName1'] = '';
            $seorderentryData[$k]['FAuxName2'] = '';
            $seorderentryData[$k]['FAuxName3'] = '';

            $seorderentryData[$k]['FBatchNoA'] = '';
            $seorderentryData[$k]['FBOSQty2'] = 0;
            $seorderentryData[$k]['FPriceWB'] = $FExchangeRate == 1 ? 0 : $v['fprice'];
            $seorderentryData[$k]['FAmountWB'] = $FExchangeRate == 1 ? 0 : $fqty * $v['fprice'];
            $seorderentryData[$k]['FWBHL'] = $FExchangeRate == 1 ? 0 : $FExchangeRate;

            $seorderentryData[$k]['FWBMC'] = '';
            $seorderentryData[$k]['FBOMNumber'] = $FBOMNumber;
            //$seorderentryData[$k]['FCustOrderNo']=$v['fcustorderno'];
            $seorderentryData[$k]['FStkQty'] = 0;
            //$seorderentryData[$k]['FCustItemName']=$v['fcustitemname'];//客户产品名称

        }
//            dd($seorderentryData);ICStockBill
        $ICStockBillIns = DB::table('ICStockBill')->insert($seorderData);
        $ICStockBillEntryEntryIns = DB::table('ICStockBillEntry')->insert($seorderentryData);

        if ($ICStockBillIns && $ICStockBillEntryEntryIns && $seoUP) {
            DB::commit();
			$sql = "update icstockbill set FBillSumAmount='{$FBillSumAmount}' where finterid = {$finterid}";
            SqlServerUtil::execSql($this->SqlServer,$sql);
            //$sql_2 = "exec UpdateStkQty 21,{$finterid},-1";
            //SqlServerUtil::exec($this->SqlServer, $sql_2);
			$this->UpdatePurSaleBillYJSDate(21,$finterid,1);
            //判断支付方式不等于挂账或公司名不是《现金客户-》开始
            if($PayName != '挂账' || $arrCompanyName){
                $request->merge(['billNo'=> $FBillNo]);
                $request->merge(['accountName'=> $PayName]);
                $this->receipt($request,$FTaxRate);
            }
            returnData(0, '成功', ['fbillno' => $FBillNo]);
        } else {
            DB::rollback();
            returnData(400, '失败');
        }
    }
    //
	private function ycInStock(Request $request)
    {
        $this->log(__FUNCTION__,'----1----'.$request);
        $type = $request->get('type');
        if ($type != 'outstock') {
            returnData(400, '出库单参数不正确');
        }
        //这里默认客户 ---华强云仓
        //单据类型 1-销售订单 2-调拨出库
//        $OrderType = $request->get('OrderType');
//        if ($OrderType != 1 || $OrderType != 2) {
//            returnData('400', '单据类型不正确');
//        }

        //获取客户
//        $fcutomerName = $request->get('fcutomername') ?? '华强云仓';
        $CompanyName  = $request->get('CompanyName') ?? '华强云仓';
        //处理公司名是《现金客户-》开始的数据为该条件成立触发往来收款单 20200602卢婷要求
        //类似SO2006011617030950这个单的客户栏归属《现金客户-张志强》（因为没有这个客户，所以我们默认为-华强云仓）
        //或结算方式为现金的（这个结算方式为现金：是根据该客户信息预设的结算方式），
        //满足《现金客户-》该条件的都进入往来收款
        $arrCompanyName = explode('-',$CompanyName)[0];
        if($arrCompanyName != '现金客户'){
            $arrCompanyName = '';
        }
        //returnData(400, __line__,$arrCompanyName);
        $PayName = $request->get('PayName') ?? '挂账';
        $Delivery = $request->get('Delivery') ?? '送货';
        $Mobile = $request->get('Mobile');
        $Contact = $request->get('Contact');
        $AccountUUID = $request->get('AccountUUID');
        $AccountMobile = $request->get('AccountMobile');
        $CustomerUUID = $request->get('CustomerUUID');
//        $saleidname = $request->get('SaleidName') ?? "现销";
//        $settlementidname = $request->get('settlementidname') ?? "现金";
//        $deliveryidname = $request->get('deliveryidname') ?? "送货";
//        $fcurrencyidname = $request->get('fcurrencyidname') ?? "人民币";
//        $stocknameidname = $request->get('stocknameidname') ?? "深圳仓";
        $FBillNoGS = $request->get('OrderNO');
        //OrderType --1 销售订单，，2--调拨出库
        if (empty($FBillNoGS)) {
            returnData(400, '单据号不能为空');
        }
        $OrderType = $request->get('OrderType');
        //TradingMode 交易方式 0-无 1-华强代售 2-商家自营
        $TradingMode = $request->get('TradingMode');
        $PayTime = $request->get('PayTime');
        $pagam = $request->all();
        $patten = "/^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/";
        if (!preg_match($patten, $PayTime)) {
            returnData(400, '销售订单时间格式不正确');
        }
        $OrderType = 2;

        $fbillnoxmArr = SqlServerUtil::exec($this->SqlServer, "SELECT v1.finterid,v1.fbillno,v1.FBillNoGS FROM ICStockBill v1 WHERE v1.FBillNoGS = '{$FBillNoGS}'", 2);
        if ($fbillnoxmArr) {
            returnData(400, '单据单号已存在！ ');
        }
        $Time = $request->get('Time');
        if (!preg_match($patten, $Time)) {
            returnData(400, '制单时间格式不正确');
        }
        //税率
        $fdiscountrate = 0;

        $json = $request->get('Details');
        //$entryData = json_decode($json,true);
        $entryData = $json;
        if (is_array($entryData) && count($entryData) > 0) {
            $res_SystemProfile = SqlServerUtil::exec($this->SqlServer, "select fvalue from t_SystemProfile where FKey ='FHQYCDBInStockName'", 2);
            $sql="select FItemID from t_stock where FName = '{$res_SystemProfile['fvalue']}'";
            $sql = iconv('UTF-8', 'GBK', $sql);
            $res_fdcstockid = SqlServerUtil::exec($this->SqlServer, $sql,2);
            $sql="select FItemID from t_stock where FName = '华强云仓'";
            $sql = iconv('UTF-8', 'GBK', $sql);
            $res_fscstockid = SqlServerUtil::exec($this->SqlServer, $sql,2);
            $entry_wl = array_column($entryData, 'MaterialCode');
            $where_wl = '';
            foreach ($entry_wl as $k => $ewl) {
                $sql = "select tme.FName as funitidname,a.FParentID,a.fitemid,a.fnumber,a.fname,a.funitid,a.fmodel,a.fhelpcode,a.fnote,a.FAlias,a.fsaleprice,a.Fdefaultloc,tst.fname as fdefaultlocname from t_icitem a
    			left join t_stock tst on tst.fitemid=a.fdefaultloc
    			LEFT JOIN t_measureunit tme on a.funitid=tme.fmeasureunitid
    			where 1=1 and a.FHelpCode= '{$ewl}' and a.fdeleted=0 ";
                $wuliao = SqlServerUtil::exec($this->SqlServer, $sql, 2);
                if (empty($wuliao)) {
                    returnData(400, '物料代号不正确');
                    break;
                }
                $entryData[$k]['fnumber_wl'] = $wuliao['fitemid'];
                $entryData[$k]['fscstockid'] =$res_fscstockid['FItemID'];
                $entryData[$k]['fdcstockid'] = $res_fdcstockid['FItemID'];
                //$entryData[$k]['funitid'] = empty($danwei) ? 69 : $wuliao['funitid'];
                $entryData[$k]['funitid'] = $wuliao['funitid'];
            }
            //判断数量
            $totalmoney=0;
            foreach ($entryData as $k => $v) {
                if (!isIntNum($v['Quantity'])) {
                    returnData(400, '数量不为空 或格式不正确');
                    break;
                }
                if (!isFloatNum($v['Price'])) {
                    returnData(400, '单价不为空 或格式不正确');
                    break;
                }
                $entryData[$k]['fqty'] = $v['Quantity'];
                $entryData[$k]['fprice'] = $v['Price'];

                $totalmoney +=$v['Quantity']*$v['Price'];

            }
        } else {
            returnData(400, '参数错误');
        }
        //获取配送方式标示ID
        $sqlStr = iconv('UTF-8', 'GBK', "SELECT FInterID,FName  FROM t_submessage WHERE  ftypeid in (32) and fdeleted=0 and FName = '".$Delivery."'");
        $FFetchStyle = SqlServerUtil::exec($this->SqlServer,$sqlStr,2 );
        //处理客户信息
        //======================================================处理客户信息start============================================================
        $fcutomerName = iconv('UTF-8', 'GBK', $CompanyName);
        //判断客户 select FItemID as customerid,FStatus,FName,FNumber,FAddress,FCity,FProvince,FCountry,FPhone,FEmail,fsetid,FValueAddRate,FxmNumber from t_organization
        $customer = SqlServerUtil::exec($this->SqlServer, "select fnumber,FItemID,FName,FAddress,FPhone,FMobileNumber,FContact,FSetID,FSaleID,Femployee,Fdepartment,FcurrencyID,FValueAddRate from t_organization where Fname='{$fcutomerName}' ", 2);
        //解决非挂账客户栏归属华强云仓20200602卢婷要求
        //类似SO2006011742103547这个单的客户栏归属《华强云仓》条件是非挂账的
        if($PayName != '挂账'){
            $customer = '';
        }
        if (empty($customer)) {
//            returnData(400, 'ERP客户不正确');
            $fcutomerName = iconv('UTF-8', 'GBK', "华强云仓");
            $customer = SqlServerUtil::exec($this->SqlServer, "select fnumber,FItemID,FName,FAddress,FPhone,FMobileNumber,FContact,FSetID,FSaleID,Femployee,Fdepartment,FcurrencyID,FValueAddRate from t_organization where Fname='{$fcutomerName}' ", 2);
        }

        $customerid = $customer['FItemID'];

        //联系人
        if(empty($Contact)){
            $flxr = $customer['FContact'];
            if ($request->has('flxr') and $request->flxr != '' && !empty($request->flxr)) {
                $flxr = $request->flxr;
            }
        }else{
            $flxr = $Contact;
        }
        //客户联系电话
        if(empty($Mobile)){
            $flxrdh = $customer['FMobileNumber'];
            if ($request->has('flxrdh') and $request->flxrdh != '' && !empty($request->flxrdh)) {
                $flxrdh = $request->flxrdh??$customer['FPhone'];
            }
        }else{
            $flxrdh = $Mobile;
        }

        //地址
        $ffetchadd = $customer['FAddress'];
        if ($request->has('ffetchadd') and $request->ffetchadd != '' && !empty($request->ffetchadd)) {
            $ffetchadd = $request->ffetchadd;
        }
        $Salesid = $customer['FSaleID'];
        $fempid = $customer['Femployee'];
        $fdeptid = $customer['Fdepartment'];
        $Fcurrencyid = $customer['FcurrencyID'];
        $Settlementid = $customer['FSetID'];
        //======================================================处理客户信息end============================================================
        //登录账户 -- 默认manager
        $FUserID = 16394;

        $FExchangeRate = $request->get('fexchangerate') ?? 1;
        if (empty($FExchangeRate)) {
            $FExchangeRate = 1;
        }

        /* //仓库名称
         if($request->has('stocknameid') and $request->stocknameid != '' && !empty($request->stocknameid)){
         $Stock = SqlServerUtil::exec($this->SqlServer, "select fitemid,fnumber,fname from t_stock where fname='{$Stocknameid}'",2);

         if(empty($Stock)){
         returnData('400','仓库设置不正确');
         }
         $Stocknameid = $Stock['fitemid'];
         }else{
         $Stocknameid =70; //默认 70----0001--深圳仓
         } */

        //业务员
        if ($request->has('SalesName') and $request->SalesName != '' && !empty($request->SalesName)) {
            $Femployeestr = iconv('UTF-8', 'GBK', $request->SalesName);
            $FemployeeName = SqlServerUtil::exec($this->SqlServer, "select FItemID,FName from t_emp where fitemid>0 and FName ='{$Femployeestr}'", 2);
            if (empty($FemployeeName)) {
                returnData(400, '销售员不正确');
            }
            $fempid = $FemployeeName['FItemID'];
        }
        //制单员fbilleridname
        //处理指定制单员过程
        $fbillerid = 0;
        $res_user = SqlServerUtil::exec($this->SqlServer, "select fvalue from t_SystemProfile where FKey ='FHQYCGenBillUser'", 2);
        if ($res_user) {
            $sql = "select FUserID,FName from  t_user where FUserID>0 and FName ='{$res_user['fvalue']}'";
            $sql = iconv('UTF-8', 'GBK', $sql);
            $FFName = SqlServerUtil::exec($this->SqlServer, $sql, 2);
            $fbillerid = isset($FFName['FUserID']) ? $FFName['FUserID'] : 16394;
        }else{
            $FFName = SqlServerUtil::exec($this->SqlServer, "select FUserID,FName from  t_user where FUserID>0 and FName ='manager'", 2);
            $fbillerid = isset($FFName['FUserID']) ? $FFName['FUserID'] : 16394;
        }
        //处理含税/未税

        $res_FText = SqlServerUtil::exec($this->SqlServer, "select fvalue from t_SystemProfile where FKey ='FSaleOutTaxFlagFld'", 2);
        $FTaxRate = 0;
        $Fdiscountrate=0;
        if ($res_FText) {
            if($TradingMode == 1){
                //含税
                $FTaxRate = 13;
            }else{
                //未税
                $FTaxRate = 0;
            }
        }
        //审核员fcheckeridname
        $fcheckerid = 16394;
        if ($request->has('fcheckeridname') and $request->fcheckeridname != '' && !empty($request->fcheckeridname)) {
            $FcheckeridnameStr = iconv('UTF-8', 'GBK', $request->fcheckeridname);
            $FcheckeridName = SqlServerUtil::exec($this->SqlServer, "select FUserID,FName from  t_user where FUserID>0 and FName ='{$FcheckeridnameStr}'", 2);
            if ($FcheckeridName) {
                $fcheckerid = $FcheckeridName['FUserID'];
            }
        }
        $fstockid = 0;

        //获取出库标示ID
        $sqlStr = iconv('UTF-8', 'GBK', "select finterid from t_submessage where ftypeid=38 and fdeleted=0 and FName = '华强出库' order by fid ");
        $FBillTypeID = SqlServerUtil::exec($this->SqlServer,$sqlStr,2 );
        DB::beginTransaction();
        //SEOrder--内码id
        $finterid = 1127;
        $SEOrder = SqlServerUtil::exec($this->SqlServer, "select * from ICMaxNum where FTableName ='ICStockBill' ", 2);
        if ($SEOrder) {
            $finterid = $SEOrder['FMaxNum'] + 1;
            $seoUP = DB::table('ICMaxNum')->where('FTableName', 'ICStockBill')->update(['FMaxNum' => $finterid]);
        }
        //获取内码id
        $FBillNo = $this->getFBillNo(41);
        //记录原数据集合写入摘要
        $tFExplanation = '公司名:'.$CompanyName.'付款方式:'.$PayName;
        $seorderData=[
            'FBrNo' => '',
            'FInterID' => $finterid,
            'FTranType' => 41,
            'FDate' => !empty($PayTime) ? date('Y-m-d', strtotime($PayTime)) : getCurrentTime(4), //交货日期
            'FBillNo' => $FBillNo,

            'FDeptID' => $fdeptid,
            'FEmpID' => $fempid,
            'FCurrencyID' => $Fcurrencyid ?? 1,
            'FSupplyID' => $customerid,
            'FExplanation'=>$tFExplanation,

            'FFetchAdd' => emptyStr($ffetchadd),
            'FSaleStyle' => $Salesid,
            'FBillerID' => $fbillerid,
            'FFManagerID' => 0,
            'FSettleID' => $Settlementid,
            'FExchangeRate' => $FExchangeRate,//汇率
            'FStatus' => 0, //审核
            'FMultiCheckLevel1' => 0,
            'FMultiCheckLevel2' => 0,
            'FMultiCheckDate4' => getCurrentTime(4),
            'FCurCheckLevel' => 0,
            'FRelateBrID' => 0,
            'FImport' => 0,
            'FTranStatus' => 0,
            'FSystemType' => 0,
            'FSelTranType' => 0,
            'FChildren' => 0,
            'FBrID' => 0,
            'FHookStatus' => 0,
            'fposname' => '',
            'FLXR' => emptyStr($flxr),
            'FLXRDH' => emptyStr($flxrdh),
            'FTime' => $Time,
            'FTaxRateH' => $FTaxRate, //税率
            'FEditor' => '',
            'FBillNoGS' => emptyStr($FBillNoGS),
            'FCheckerId' => 0,
            'FDateJS' => getCurrentTime(4),
            'FBillSumAmount' => $totalmoney,
            //'FCheckerId' => $fbillerid,
            //'FCheckDate' => '',
            'FFetchStyle'=>$FFetchStyle['FInterID'],
            'FBillTypeID' =>$FBillTypeID['finterid'],
            'FText1'    => $AccountUUID,
            'FText2'    => $AccountMobile,
            'FText3'    => $CustomerUUID
        ];
        if($TradingMode == 1){
            //含税
            $seorderData[$res_FText['fvalue']] =  '含税';
        }else{
            //未税
            $seorderData[$res_FText['fvalue']] =  '未税';
        }
        $seorderentryData = [];
        foreach ($entryData as $k => $v) {
            //物料id  ---BOM
            $sql = "select icb.FInterID as FBOMInterID,icb.FBOMNumber from t_icitem tic inner join icbom icb on tic.FDefaultWorkTypeID=icb.finterid where tic.FItemID ='{$v['fnumber_wl']}'";
            $bom = SqlServerUtil::exec($this->SqlServer, $sql, 2);
            $FBomInterID = 0;
            $FBOMNumber = '';
            if (!empty($bom)) {
                $FBomInterID = $bom['FBOMInterID'];
                $FBOMNumber = emptyStr($bom['FBOMNumber']);
            }

            $FTaxAmount = 0; //税额
            $FAuxTaxPrice = $v['fprice'];//含税单价
//
//                $FPriceWB = $v['fprice'];
//
//                if ($FExchangeRate != 1) {
//                    $FAmountWB = $v['fqty'] * $FPriceWB;
//                    $FAuxTaxPrice = number_format($FPriceWB * $FExchangeRate, 4, '.', '');
//                }
            $FCalTypeID = 1;
            $FAuxTaxPrice = $FAuxTaxPrice * 1000;
            $fqty = $v['fqty'] / 1000;
            //number_format($num, 2,'.',''); //10.46
            //注意前提：先设置 $FAuxqty、$FAuxTaxPrice、$FTaxRate、$Fdiscountrate
            //通过含税单价计算不含税单价
            $FConsignPrice = number_format($FAuxTaxPrice * ((100 - $Fdiscountrate) / 100), 4, '.', '');
            $FDiscountPrice = number_format($FConsignPrice / (1 + $FTaxRate / 100), 4, '.', '');
            $FAuxPriceNoTax = number_format($FDiscountPrice / ((100 - $Fdiscountrate) / 100), 4, '.', '');
            $FConsignAmount = number_format($fqty * $FConsignPrice, 2, '.', '');
            $FTaxAmount = number_format($FConsignAmount / (1 + $FTaxRate / 100) * ($FTaxRate / 100), 2, '.', '');
            $FAmountNoTax = number_format($FConsignAmount - $FTaxAmount, 2, '.', '');
            $seorderentryData[$k]['FBrNO'] = '';
            $seorderentryData[$k]['FInterID'] = $finterid;
            $seorderentryData[$k]['FEntryID'] = $k + 1;
            $seorderentryData[$k]['FItemID'] = $v['fnumber_wl'];
            $seorderentryData[$k]['FQty'] = $fqty;
            $seorderentryData[$k]['FAuxQty'] = $fqty; //实发数量
//                $seorderentryData[$k]['FPrice'] = $FAuxPrice; //没有查到 20200519注释

            $seorderentryData[$k]['FTaxRate'] = $FTaxRate;
            $seorderentryData[$k]['FTaxAmount'] = $FTaxAmount;
            $seorderentryData[$k]['FNote'] = '';
            $seorderentryData[$k]['FUnitID'] = $v['funitid'];
            $seorderentryData[$k]['FAuxCommitQty'] = 0;
//                $seorderentryData[$k]['FAuxPrice'] = $FAuxPrice; //成本单价 20200519注释


            $seorderentryData[$k]['FConsignPrice'] = $FConsignPrice; //折后含税单价
            $seorderentryData[$k]['FConsignAmount'] = $FConsignAmount;
            $seorderentryData[$k]['FUnitCost'] = $FConsignAmount;
            $seorderentryData[$k]['FAuxPriceNoTax'] = $FAuxPriceNoTax; //不含税单价
            $seorderentryData[$k]['FAmountNoTax'] = $FAmountNoTax;
            $seorderentryData[$k]['FAmount'] = 0;


            $seorderentryData[$k]['FSourceEntryID'] = 0;
            $seorderentryData[$k]['FBatchNo'] = '';
            $seorderentryData[$k]['FBomInterID'] = $FBomInterID;
            $seorderentryData[$k]['FMapNumber'] = '';
            $seorderentryData[$k]['FMapName'] = '';
            $seorderentryData[$k]['FAuxPropID'] = 0;
            $seorderentryData[$k]['FAuxTaxPrice'] = $FAuxTaxPrice; //含税单价

            $seorderentryData[$k]['FSourceTranType'] = 0;
            $seorderentryData[$k]['FSourceInterId'] = 0;
            $seorderentryData[$k]['FSourceBillNo'] = '';
            $seorderentryData[$k]['FContractInterID'] = 0;
            $seorderentryData[$k]['FContractBillNo'] = '';
            $seorderentryData[$k]['FFee'] = 0;
            $seorderentryData[$k]['FFeeHK'] = 0;
            $seorderentryData[$k]['FKFPeriod'] = 0;
            $seorderentryData[$k]['FEntryNum1'] = 0;
            $seorderentryData[$k]['FSKPH'] = '';

            $seorderentryData[$k]['FSCStockID'] = $v['fscstockid'];
            $seorderentryData[$k]['FDCStockID'] = $v['fdcstockid'];
            $seorderentryData[$k]['FCalTypeID'] = 1;
            $seorderentryData[$k]['FCostOBJID'] = 0;
            $seorderentryData[$k]['FCostObjGroupID'] = 0;
            $seorderentryData[$k]['FAuxQtyMust'] = 0;
            $seorderentryData[$k]['FAuxPriceRef'] = 0;
            $seorderentryData[$k]['fbakqty'] = 0;

            $seorderentryData[$k]['FDiscountPrice'] = $FDiscountPrice;
            $seorderentryData[$k]['FCustItemModel'] = '';
            $seorderentryData[$k]['FXLH'] = '';
            $seorderentryData[$k]['FUPC'] = '';
            $seorderentryData[$k]['FEntryText1'] = '';
            $seorderentryData[$k]['FEntryText2'] = '';
            $seorderentryData[$k]['FEntryText3'] = '';

            $seorderentryData[$k]['FBOSUnitID'] = 0;
            $seorderentryData[$k]['FBOSQty'] = 0;
            $seorderentryData[$k]['fbosqtyrest'] = 0;
            $seorderentryData[$k]['FBOSCoe'] = 0;
            $seorderentryData[$k]['FBOSPrice'] = 0;
            $seorderentryData[$k]['FGrossWeight'] = 0;
            $seorderentryData[$k]['FTotalWeight'] = 0;
            $seorderentryData[$k]['FSize'] = 0;
            $seorderentryData[$k]['FTotalSize'] = 0;

            $seorderentryData[$k]['FAuxName1'] = '';
            $seorderentryData[$k]['FAuxName2'] = '';
            $seorderentryData[$k]['FAuxName3'] = '';

            $seorderentryData[$k]['FBatchNoA'] = '';
            $seorderentryData[$k]['FBOSQty2'] = 0;
            $seorderentryData[$k]['FPriceWB'] = $FExchangeRate == 1 ? 0 : $v['fprice'];
            $seorderentryData[$k]['FAmountWB'] = $FExchangeRate == 1 ? 0 : $fqty * $v['fprice'];
            $seorderentryData[$k]['FWBHL'] = $FExchangeRate == 1 ? 0 : $FExchangeRate;

            $seorderentryData[$k]['FWBMC'] = '';
            $seorderentryData[$k]['FBOMNumber'] = $FBOMNumber;
            //$seorderentryData[$k]['FCustOrderNo']=$v['fcustorderno'];
            $seorderentryData[$k]['FStkQty'] = 0;
            //$seorderentryData[$k]['FCustItemName']=$v['fcustitemname'];//客户产品名称

        }
//            dd($seorderentryData);ICStockBill
        $ICStockBillIns = DB::table('ICStockBill')->insert($seorderData);
        $ICStockBillEntryEntryIns = DB::table('ICStockBillEntry')->insert($seorderentryData);

        if ($ICStockBillIns && $ICStockBillEntryEntryIns && $seoUP) {
            DB::commit();
            returnData(0, '成功', ['fbillno' => $FBillNo]);
        } else {
            DB::rollback();
            returnData(400, '失败');
        }
    }
	//库存查询
    private function ICInventorybal(Request $request){
		$this->log(__FUNCTION__,'----1----'.$request);
        $type = $request->get('type');
        if($type != 'querystock'){
//            return response()->json(Common::errorResponseHQ(400,'URL参数有误！'));
            returnData(400, 'URL参数有误');
        }
        $page= $request ->get('page');
        if(!isset($page)) $page =1;
        $limit= $request ->get('limit');
        if(!isset($limit)) $limit =1000;
        $pages = ($page-1)* $limit;
        $res =[];
        $fnameStr='';
        $fbillnoStr = '';
        $timeStr = '' ;
        $keywordStr = '';
        $wuliaoStr = '';
        $fitemidnumberStr ='';
        $fwlStr='';
        //
        //$request->merge(['fname'=> '华强云仓']);
        //
        //$fname = $request->fname ??'华强云仓';
        //$fnameStr =" and tst.FName = '{$fname}'";
        //if($request->has('fname') && $request->fname != '' && !empty($request->fname)){
        //    $fname =iconv('UTF-8', 'GBK', $request->fname);
        //    $fnameStr =" and tst.FName = '{$fname}'";
        //}
//            if($request->has('fnumber') && $request->fnumber != '' && !empty($request->fnumber)){
//                $fwl = $request->fnumber;
//                $fwlData=explode(',',$fwl);
//                $str ='';
//                foreach ($fwlData as $v){
//                    $v=iconv('UTF-8', 'GBK',$v);
//                    $str .="'".$v."',";
//                }
//                $fwl = rtrim($str,',');
//                $fwlStr =" and tic.fnumber in ({$fwl})";
//            }
        $tmp_fnumber = "";
        if($request->has('MaterialCodes') && $request->MaterialCodes != '' && !empty($request->MaterialCodes)){
            foreach ($request->MaterialCodes as $k => $v){
                $tmp_fnumber .= "'".$v."',";
            }
            $tmp_fnumber = rtrim($tmp_fnumber,',');
        }
        if(!empty($tmp_fnumber)){
            $fwlStr =" and tic.FHelpCode in ({$tmp_fnumber})";
        }
        /*
        if ($request->has('keyword') and $request->keyword != '' and !empty($request->keyword)) {
            $keyword =iconv('UTF-8', 'GBK', $request->keyword);
            $keywordStr=" and (tst.fname like '%{$keyword}%' or tic.fnumber like '%{$keyword}%' or tic.fname like '%{$keyword}%' or tic.fmodel like '%{$keyword}%'  )";
        }
        if ($request->has('fitemidnumber') and $request->fitemidnumber != '' and !empty($request->fitemidnumber)) {
            $fitemidnumber = iconv('UTF-8', 'GBK', $request->fitemidnumber);
            $fitemidnumberStr=" and tic.fnumber like '%{$fitemidnumber}%'";
        }
        if ($request->has('wuliao') and $request->wuliao != '' and !empty($request->wuliao)) {
            $wuliao = iconv('UTF-8', 'GBK', $request->wuliao);
            $wuliaoStr=" and (tic.fnumber like '%{$wuliao}%' or tic.fname like '%{$wuliao}%' or tic.fmodel like '%{$wuliao}%')";
        } */
        $sort="desc";
        if ($request->has('sort') and $request->sort == 2 and !empty($request->sort)) {
            $sort="asc";
        }
//            $sql = "select top $limit * from (
//                    SELECT
//                    row_number() over(order by tst.fnumber {$sort},tic.FItemID {$sort}) as rownumber,
//                    tst.FName as fstockidname,tic.FNumber as fitemidnumber,tic.FName as fitemidname,tic.FModel
//                    ,u1.fqty,tme.fname as funitidname
//                    from ICInventorybal u1
//                    left join t_icitem tic on u1.fitemid=tic.fitemid
//                    left join t_stock tst on tst.fitemid=u1.fstockid
//                    left join t_measureunit tme on tme.fitemid=tic.funitid
//                    where 1=1 {$fwlStr} {$fnameStr} ) temp_row
//                    where rownumber>(($page-1)*$limit)";
        //        $sql = "select top $limit * from (
//                    SELECT
//                    tic.FHelpCode as MaterialCode ,convert(int,u1.fqty) as Quantity,convert(int,(u1.fqty - u1.fxsjhl)) as AvailableQuantity,tme.fname as Unit
//                    from ICInventorybal u1
//                    left join t_icitem tic on u1.fitemid=tic.fitemid
//                    left join t_stock tst on tst.fitemid=u1.fstockid
//                    left join t_measureunit tme on tme.fitemid=tic.funitid
//                    where 1=1 {$fwlStr} {$fnameStr} ) temp_row";

        $sql = "SELECT tic.FHelpCode as MaterialCode,tme.fname as Unit,
				sum(case when tst.fname='华强云仓' then u1.fqty else 0 end) as Quantity,
				sum(case when tst.fname='华强云仓' then (u1.fqty - u1.fxsjhl) else 0 end) as AvailableQuantity,
				sum(case when tst.fname<>'华强云仓' then u1.fqty else 0 end) as Quantityb,
				sum(case when tst.fname<>'华强云仓' then (u1.fqty - u1.fxsjhl) else 0 end) as AvailableQuantityb
				from ICInventorybal u1
				left join t_icitem tic on u1.fitemid=tic.fitemid
				left join t_stock tst on tst.fitemid=u1.fstockid
				left join t_measureunit tme on tme.fitemid=tic.funitid
				where 1=1 {$fwlStr} {$fnameStr} group by tic.FHelpCode,tme.fname";
	
		$sql=iconv('UTF-8', 'GBK',$sql);
		$this->log(__FUNCTION__,'----2----'.$sql);
        $res = SqlServerUtil::exec($this->SqlServer,$sql);
        $t_res = [];
        if($res === false){
//            return response()->json(Common::errorResponseHQ(400,'服务器错误'));
            returnData(400, '服务器错误');
        }else{
            foreach ($res as $k => $v){
                $t_res[$k]['MaterialCode'] = $v['MaterialCode'];
                $t_res[$k]['Quantity'] = $v['Quantity']*1000;
//                $t_res[$k]['AvailableQuantity'] = $v['AvailableQuantity']*1000;
                $t_res[$k]['AvailableQuantity'] = $v['Quantityb']*1000;
//                $t_res[$k]['Quantityb'] = $v['Quantityb']*1000;
//                $t_res[$k]['AvailableQuantityb'] = $v['AvailableQuantityb']*1000;
                $t_res[$k]['Unit'] = 'PCS';
            }
        }
//        file_put_contents("C:\\phpstudy_pro\\wwwroot\\huaqiangyuncangjiekou\\app\\Http\\Controllers\\Api\\test.txt",json_encode($res));
//        $countSql ="select count(*) total from ICInventorybal u1 left join t_icitem tic on u1.fitemid=tic.fitemid
//                        left join t_stock tst on tst.fitemid=u1.fstockid
//                        left join t_measureunit tme on tme.fitemid=tic.funitid
//                        where 1=1  {$fwlStr} {$fnameStr} ";
//        $count = SqlServerUtil::exec($this->SqlServer, $countSql);
//            $this->response['total'] = $count ? $count[0]['total']:0;
//
//            $this->response['size'] = 1;
//            $last_page =0;
//            if($count && count($count)>0){
//                $last_page = ceil($count[0]['total']/$limit);
//                $this->response['size'] = $limit;
//            }
//            $this->response['result']= $res;
//            $this->response['last_page'] =$last_page;
        returnData(0, '成功', $t_res);
//        $this->response['Data']= $res;
//        return response()->json($this->response);
    }
    public function icitemList(Request $request){
        $page= $request ->get('page') ? $request ->get('page') : 1;
        $limit= $request ->get('limit') ? $request ->get('limit') : 100;
        $pages = ($page-1)* $limit;
        $fnameStr = '';
        $fwlStr ='';
        $fname =$request->fname ?$request->fname:'物流一部';
        if($request->has('fname') && $request->fname != '' && !empty($request->fanme)){
            $fnameStr =" and tst.FName = '{$fname}'";
        }

        $fwlStr ='';
        if(empty($request->get('fmodel'))){
            returnData(400,'物料编号不为空');
        }
        if($request->has('fmodel') && $request->fmodel != '' && !empty($request->fmodel)){
            $fwl = $request->fmodel;
            $fwlData=explode(',',$fwl);
            $str ='';
            foreach ($fwlData as $v){
                $str .="'".$v."',";
            }
            $fwl = rtrim($str,',');
            $fwlStr =" and a.fnumber in ({$fwl})";
        }
        $sql="(select isnull(v1.FQty,0) FQty,tst.FName as fstockidname, tme.fname as funitidname,tme.fcoefficient
,a.fnumber as fitemidnumber,a.fname as fitemidname,a.fmodel from t_icitem a
left join t_measureunit tme on a.funitid=tme.fmeasureunitid
left join t_stock tst on tst.fitemid=a.fdefaultloc
left join (select sum(ic.Fqty) as FQty,FItemID from ICInventorybal ic group by FItemID ) v1 on v1.fitemid=a.fitemid
where 1=1 and 2=2 and a.fdeleted=0 {$fnameStr} {$fwlStr}) as cc";
        $result=[];
        $res=DB::table(DB::raw($sql))->orderBy('fitemidnumber','desc')->paginate($limit)->toArray();//获取所有数据

        foreach ($res['data'] as $k => $user) {
            $result[$k]= Common::object_array($user);
        }
        $arr =[
            'current_page'=>$res['current_page'],
            'data'=>$result,
            "last_page" => $res['last_page'],
            "limit" => $limit,
            "total" => $res['total'],
        ];
        returnData('200','成功',$arr);
    }
    
    /**
    * 聚一科技 ^_^
    * /api/tiaobo
    * @date: 2020年7月25日
    * @author: lq
    * @version:App V2.0
    */
    public function tiaobo(Request $request){
    	$this->log(__FUNCTION__,'----1----'.$request);
//     	$type = $request->get('type');
//     	if ($type != 'outstock') {
//     		returnData(400, '出库单参数不正确');
//     	}
    	
    	$CompanyName  = $request->get('ApplyUser') ?? '华强云仓'; //客户
    	$Mobile = $request->get('Mobile'); //提货人手机号
    	$Contact = $request->get('Contact'); //联系人
    	$Remark = $request->get('Remark'); //备注
    	
//     	if (empty($FBillNoGS)) {
//     		returnData(400, '单据号不能为空');
//     	}
    	//OrderType --1 销售订单，，2--调拨出库
    	//$OrderType = $request->get('OrderType');
    	//TradingMode 交易方式 0-无 1-华强代售 2-商家自营
    	$TradingMode = $request->get('TradingMode');
    	//$PayTime = $request->get('PayTime');
    	$pagam = $request->all();
//     	$patten = "/^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/";
//     	if (!preg_match($patten, $PayTime)) {
//     		returnData(400, '销售订单时间格式不正确');
//     	}
    	
//     	$fbillnoxmArr = SqlServerUtil::exec($this->SqlServer, "SELECT v1.finterid,v1.fbillno,v1.FBillNoGS FROM ICStockBill v1 WHERE v1.FBillNoGS = '{$FBillNoGS}'", 2);
//     	if ($fbillnoxmArr) {
//     		returnData(400, '单据单号已存在！ ');
//     	}
//     	$Time = $request->get('Time');
//     	if (!preg_match($patten, $Time)) {
//     		returnData(400, '制单时间格式不正确');
//     	}
    	//税率
    	$fdiscountrate = 0;
    	
    	$json = $request->get('Details');
    	//$entryData = json_decode($json,true);
    	$entryData = $json;
    	if (is_array($entryData) && count($entryData) > 0) {
    		//MaterialCode  -- Quantity  -- Unit
    		$res_SystemProfile = SqlServerUtil::exec($this->SqlServer, "select fvalue from t_SystemProfile where FKey ='FHQYCDBInStockName'", 2);
    		$sql="select FItemID from t_stock where FName = '{$res_SystemProfile['fvalue']}'";
    		$sql = iconv('UTF-8', 'GBK', $sql);
    		$res_fdcstockid = SqlServerUtil::exec($this->SqlServer, $sql,2);
    		$sql="select FItemID from t_stock where FName = '华强云仓'";
    		$sql = iconv('UTF-8', 'GBK', $sql);
    		$res_fscstockid = SqlServerUtil::exec($this->SqlServer, $sql,2);
    		$entry_wl = array_column($entryData, 'MaterialCode'); //供应商料号
    		$where_wl = '';
    		foreach ($entry_wl as $k => $ewl) {
    			$sql = "select tme.FName as funitidname,a.FParentID,a.fitemid,a.fnumber,a.fname,a.funitid,a.fmodel,a.fhelpcode,a.fnote,a.FAlias,a.fsaleprice,a.Fdefaultloc,tst.fname as fdefaultlocname from t_icitem a
    			left join t_stock tst on tst.fitemid=a.fdefaultloc
    			LEFT JOIN t_measureunit tme on a.funitid=tme.fmeasureunitid
    			where 1=1 and a.FHelpCode= '{$ewl}' and a.fdeleted=0 ";
    			$wuliao = SqlServerUtil::exec($this->SqlServer, $sql, 2);
    			if (empty($wuliao)) {
    				returnData(400, '物料代号不正确');
    				break;
    			}
    			$entryData[$k]['fnumber_wl'] = $wuliao['fitemid'];
    			$entryData[$k]['fscstockid'] =$res_fscstockid['FItemID'];// 源
    			$entryData[$k]['fdcstockid'] = $res_fdcstockid['FItemID'];// 目的
    			$entryData[$k]['funitid'] = $wuliao['funitid'];
    		}
    		//判断数量
    		$totalmoney=0;
    		foreach ($entryData as $k => $v) {
    			if (!isIntNum($v['Quantity'])) {
    				returnData(400, '数量不为空 或格式不正确');
    				break;
    			}
//     			if (!isFloatNum($v['Price'])) {
//     				returnData(400, '单价不为空 或格式不正确');
//     				break;
//     			}
    			$entryData[$k]['fqty'] = $v['Quantity'];
    			$entryData[$k]['fprice'] = 0; //$v['Price']
    			
    			///$totalmoney +=$v['Quantity']*$v['Price'];
    			
    		}
    	} else {
    		returnData(400, '参数错误');
    	}
    	//获取配送方式标示ID
    	//$sqlStr = iconv('UTF-8', 'GBK', "SELECT FInterID,FName  FROM t_submessage WHERE  ftypeid in (32) and fdeleted=0 and FName = '".$Delivery."'");
    	//$FFetchStyle = SqlServerUtil::exec($this->SqlServer,$sqlStr,2 );
    	//处理客户信息
    	//======================================================处理客户信息start============================================================
    	/* $fcutomerName = iconv('UTF-8', 'GBK', $CompanyName);
    	//判断客户 select FItemID as customerid,FStatus,FName,FNumber,FAddress,FCity,FProvince,FCountry,FPhone,FEmail,fsetid,FValueAddRate,FxmNumber from t_organization
    	$customer = SqlServerUtil::exec($this->SqlServer, "select fnumber,FItemID,FName,FAddress,FPhone,FMobileNumber,FContact,FSetID,FSaleID,Femployee,Fdepartment,FcurrencyID,FValueAddRate from t_organization where Fname='{$fcutomerName}' ", 2);
    	//解决非挂账客户栏归属华强云仓20200602卢婷要求
    	//类似SO2006011742103547这个单的客户栏归属《华强云仓》条件是非挂账的
    	if($PayName != '挂账'){
    		$customer = '';
    	}
    	if (empty($customer)) {
    		//            returnData(400, 'ERP客户不正确');
    		$fcutomerName = iconv('UTF-8', 'GBK', "华强云仓");
    		$customer = SqlServerUtil::exec($this->SqlServer, "select fnumber,FItemID,FName,FAddress,FPhone,FMobileNumber,FContact,FSetID,FSaleID,Femployee,Fdepartment,FcurrencyID,FValueAddRate from t_organization where Fname='{$fcutomerName}' ", 2);
    	}
    	
    	$customerid = $customer['FItemID'];
    	
    	//联系人
    	if(empty($Contact)){
    		$flxr = $customer['FContact'];
    		if ($request->has('flxr') and $request->flxr != '' && !empty($request->flxr)) {
    			$flxr = $request->flxr;
    		}
    	}else{
    		$flxr = $Contact;
    	}
    	//客户联系电话
    	if(empty($Mobile)){
    		$flxrdh = $customer['FMobileNumber'];
    		if ($request->has('flxrdh') and $request->flxrdh != '' && !empty($request->flxrdh)) {
    			$flxrdh = $request->flxrdh??$customer['FPhone'];
    		}
    	}else{
    		$flxrdh = $Mobile;
    	}
    	
    	//地址
    	$ffetchadd = $customer['FAddress'];
    	if ($request->has('ffetchadd') and $request->ffetchadd != '' && !empty($request->ffetchadd)) {
    		$ffetchadd = $request->ffetchadd;
    	}
    	$Salesid = $customer['FSaleID'];
    	$fempid = $customer['Femployee'];
    	$fdeptid = $customer['Fdepartment'];
    	$Fcurrencyid = $customer['FcurrencyID'];
    	$Settlementid = $customer['FSetID']; */
    	//======================================================处理客户信息end============================================================
    	//登录账户 -- 默认manager
    	$FUserID = 16394;
    	
    	$FExchangeRate = $request->get('fexchangerate') ?? 1;
    	if (empty($FExchangeRate)) {
    		$FExchangeRate = 1;
    	}
    	
//     	//业务员
//     	if ($request->has('SalesName') and $request->SalesName != '' && !empty($request->SalesName)) {
//     		$Femployeestr = iconv('UTF-8', 'GBK', $request->SalesName);
//     		$FemployeeName = SqlServerUtil::exec($this->SqlServer, "select FItemID,FName from t_emp where fitemid>0 and FName ='{$Femployeestr}'", 2);
//     		if (empty($FemployeeName)) {
//     			returnData(400, '销售员不正确');
//     		}
//     		$fempid = $FemployeeName['FItemID'];
//     	}
    	//审核员fcheckeridname
//     	$fcheckerid = 16394;
//     	if ($request->has('fcheckeridname') and $request->fcheckeridname != '' && !empty($request->fcheckeridname)) {
//     		$FcheckeridnameStr = iconv('UTF-8', 'GBK', $request->fcheckeridname);
//     		$FcheckeridName = SqlServerUtil::exec($this->SqlServer, "select FUserID,FName from  t_user where FUserID>0 and FName ='{$FcheckeridnameStr}'", 2);
//     		if ($FcheckeridName) {
//     			$fcheckerid = $FcheckeridName['FUserID'];
//     		}
//     	}
//     	//处理指定制单员过程
//     	$fbillerid = 0;
//     	$res_user = SqlServerUtil::exec($this->SqlServer, "select fvalue from t_SystemProfile where FKey ='FHQYCGenBillUser'", 2);
//     	if ($res_user) {
//     		$sql = "select FUserID,FName from  t_user where FUserID>0 and FName ='{$res_user['fvalue']}'";
//     		$sql = iconv('UTF-8', 'GBK', $sql);
//     		$FFName = SqlServerUtil::exec($this->SqlServer, $sql, 2);
//     		$fbillerid = isset($FFName['FUserID']) ? $FFName['FUserID'] : 16394;
//     	}else{
//     		$FFName = SqlServerUtil::exec($this->SqlServer, "select FUserID,FName from  t_user where FUserID>0 and FName ='manager'", 2);
//     		$fbillerid = isset($FFName['FUserID']) ? $FFName['FUserID'] : 16394;
//     	}
    	//处理含税/未税
    	
    	$res_FText = SqlServerUtil::exec($this->SqlServer, "select fvalue from t_SystemProfile where FKey ='FSaleOutTaxFlagFld'", 2);
    	$FTaxRate = 0;
    	$Fdiscountrate=0;
    	if ($res_FText) {
    		if($TradingMode == 1){
    			//含税
    			$FTaxRate = 13;
    		}else{
    			//未税
    			$FTaxRate = 0;
    		}
    	}
    	
    	
//     	//获取出库标示ID
//     	$sqlStr = iconv('UTF-8', 'GBK', "select finterid from t_submessage where ftypeid=38 and fdeleted=0 and FName = '华强出库' order by fid ");
//     	$FBillTypeID = SqlServerUtil::exec($this->SqlServer,$sqlStr,2 );
    	DB::beginTransaction();
    	//SEOrder--内码id
    	$finterid = 1127;
    	$SEOrder = SqlServerUtil::exec($this->SqlServer, "select * from ICMaxNum where FTableName ='ICStockBill' ", 2);
    	if ($SEOrder) {
    		$finterid = $SEOrder['FMaxNum'] + 1;
    		$seoUP = DB::table('ICMaxNum')->where('FTableName', 'ICStockBill')->update(['FMaxNum' => $finterid]);
    	}
    	//获取内码id
    	$FBillNo = $this->getFBillNo(41);
    	//记录原数据集合写入摘要
    	$seorderData=[
    			'FBrNo' => '',
    			'FInterID' => $finterid,
    			'FTranType' => 41,
    			'FDate' => getCurrentTime(4), //交货日期
    			'FBillNo' => $FBillNo,
    			
    			'FMultiCheckDate4' =>getCurrentTime(), 
    			'FExplanation'=> $Remark, //备注
    			'FMarketingStyle'=> 12530,
    			'FRefType'=> 12561,
    			'FTime'=> getCurrentTime(), 
    	];
    	
    	$seorderentryData = [];
    	foreach ($entryData as $k => $v) {
    		//物料id  ---BOM
    		$sql = "select icb.FInterID as FBOMInterID,icb.FBOMNumber from t_icitem tic inner join icbom icb on tic.FDefaultWorkTypeID=icb.finterid where tic.FItemID ='{$v['fnumber_wl']}'";
    		$bom = SqlServerUtil::exec($this->SqlServer, $sql, 2);
    		$FBomInterID = 0;
    		$FBOMNumber = '';
    		if (!empty($bom)) {
    			$FBomInterID = $bom['FBOMInterID'];
    			$FBOMNumber = emptyStr($bom['FBOMNumber']);
    		}
    		
    		$FTaxAmount = 0; //税额
    		$FAuxTaxPrice = $v['fprice'];//含税单价
    		$FCalTypeID = 1;
    		$FAuxTaxPrice = $FAuxTaxPrice * 1000;
    		$fqty = $v['fqty'] / 1000;
    		//number_format($num, 2,'.',''); //10.46
    		//注意前提：先设置 $FAuxqty、$FAuxTaxPrice、$FTaxRate、$Fdiscountrate
    		//通过含税单价计算不含税单价
    		$FConsignPrice = number_format($FAuxTaxPrice * ((100 - $Fdiscountrate) / 100), 4, '.', '');
    		$FDiscountPrice = number_format($FConsignPrice / (1 + $FTaxRate / 100), 4, '.', '');
    		$FAuxPriceNoTax = number_format($FDiscountPrice / ((100 - $Fdiscountrate) / 100), 4, '.', '');
    		$FConsignAmount = number_format($fqty * $FConsignPrice, 2, '.', '');
    		$FTaxAmount = number_format($FConsignAmount / (1 + $FTaxRate / 100) * ($FTaxRate / 100), 2, '.', '');
    		$FAmountNoTax = number_format($FConsignAmount - $FTaxAmount, 2, '.', '');
    		$seorderentryData[$k]['FBrNO'] = '';
    		$seorderentryData[$k]['FInterID'] = $finterid;
    		$seorderentryData[$k]['FEntryID'] = $k + 1;
    		$seorderentryData[$k]['FItemID'] = $v['fnumber_wl'];
    		$seorderentryData[$k]['FQty'] = $fqty;
    		$seorderentryData[$k]['FAuxQty'] = $fqty; //实发数量
    		
    		$seorderentryData[$k]['FTaxRate'] = $FTaxRate;
    		$seorderentryData[$k]['FTaxAmount'] = $FTaxAmount;
    		$seorderentryData[$k]['FNote'] = '';
    		$seorderentryData[$k]['FUnitID'] = $v['funitid'];
    		$seorderentryData[$k]['FAuxCommitQty'] = 0;
    		
    		
    		$seorderentryData[$k]['FConsignPrice'] = $FConsignPrice; //折后含税单价
    		$seorderentryData[$k]['FConsignAmount'] = $FConsignAmount;
    		$seorderentryData[$k]['FAuxPriceNoTax'] = $FAuxPriceNoTax; //不含税单价
    		$seorderentryData[$k]['FAmountNoTax'] = $FAmountNoTax;
    		$seorderentryData[$k]['FAmount'] = 0;
    		
    		
    		$seorderentryData[$k]['FSourceEntryID'] = 0;
    		$seorderentryData[$k]['FBatchNo'] = '';
    		$seorderentryData[$k]['FBomInterID'] = $FBomInterID;
    		$seorderentryData[$k]['FMapNumber'] = '';
    		$seorderentryData[$k]['FMapName'] = '';
    		$seorderentryData[$k]['FAuxPropID'] = 0;
    		$seorderentryData[$k]['FAuxTaxPrice'] = $FAuxTaxPrice; //含税单价
    		
    		$seorderentryData[$k]['FSourceTranType'] = 0;
    		$seorderentryData[$k]['FSourceInterId'] = 0;
    		$seorderentryData[$k]['FSourceBillNo'] = '';
    		$seorderentryData[$k]['FContractInterID'] = 0;
    		$seorderentryData[$k]['FContractBillNo'] = '';
    		$seorderentryData[$k]['FFee'] = 0;
    		$seorderentryData[$k]['FFeeHK'] = 0;
    		$seorderentryData[$k]['FKFPeriod'] = 0;
    		$seorderentryData[$k]['FEntryNum1'] = 0;
    		$seorderentryData[$k]['FSKPH'] = '';
    		
    		$seorderentryData[$k]['FSCStockID'] = $v['fscstockid'];
    		$seorderentryData[$k]['FDCStockID'] = $v['fdcstockid'];
    		$seorderentryData[$k]['FCalTypeID'] = 1;
    		$seorderentryData[$k]['FCostOBJID'] = 0;
    		$seorderentryData[$k]['FCostObjGroupID'] = 0;
    		$seorderentryData[$k]['FAuxQtyMust'] = 0;
    		$seorderentryData[$k]['FAuxPriceRef'] = 0;
    		$seorderentryData[$k]['fbakqty'] = 0;
    		
    		$seorderentryData[$k]['FDiscountPrice'] = $FDiscountPrice;
    		$seorderentryData[$k]['FCustItemModel'] = '';
    		$seorderentryData[$k]['FXLH'] = '';
    		$seorderentryData[$k]['FUPC'] = '';
    		$seorderentryData[$k]['FEntryText1'] = '';
    		$seorderentryData[$k]['FEntryText2'] = '';
    		$seorderentryData[$k]['FEntryText3'] = '';
    		
    		$seorderentryData[$k]['FBOSUnitID'] = 0;
    		$seorderentryData[$k]['FBOSQty'] = 0;
    		$seorderentryData[$k]['fbosqtyrest'] = 0;
    		$seorderentryData[$k]['FBOSCoe'] = 0;
    		$seorderentryData[$k]['FBOSPrice'] = 0;
    		$seorderentryData[$k]['FGrossWeight'] = 0;
    		$seorderentryData[$k]['FTotalWeight'] = 0;
    		$seorderentryData[$k]['FSize'] = 0;
    		$seorderentryData[$k]['FTotalSize'] = 0;
    		
    		$seorderentryData[$k]['FAuxName1'] = '';
    		$seorderentryData[$k]['FAuxName2'] = '';
    		$seorderentryData[$k]['FAuxName3'] = '';
    		
    		$seorderentryData[$k]['FBatchNoA'] = '';
    		$seorderentryData[$k]['FBOSQty2'] = 0;
    		$seorderentryData[$k]['FPriceWB'] = $FExchangeRate == 1 ? 0 : $v['fprice'];
    		$seorderentryData[$k]['FAmountWB'] = $FExchangeRate == 1 ? 0 : $fqty * $v['fprice'];
    		$seorderentryData[$k]['FWBHL'] = $FExchangeRate == 1 ? 0 : $FExchangeRate;
    		
    		$seorderentryData[$k]['FWBMC'] = '';
    		$seorderentryData[$k]['FBOMNumber'] = $FBOMNumber;
    		$seorderentryData[$k]['FStkQty'] = 0;
    		
    	}
    	$ICStockBillIns = DB::table('ICStockBill')->insert($seorderData);
    	$ICStockBillEntryEntryIns = DB::table('ICStockBillEntry')->insert($seorderentryData);
    	
    	if ($ICStockBillIns && $ICStockBillEntryEntryIns && $seoUP) {
    		DB::commit();
    		returnData(0, '成功', ['fbillno' => $FBillNo]);
    	} else {
    		DB::rollback();
    		returnData(400, '失败');
    	}
    }
    
    /**
    * 聚一科技 ^_^
    * @date: 2020年7月31日
    * @author: lq
    * @version:App V2.0
    */
    //出库单推送
    private function ycqtckInsert(Request $request)
    {
    	$this->log(__FUNCTION__,'----1----'.$request);
    	$type = $request->get('type');
    	if ($type != 'customerbill') {
    		returnData(400, '月结账单收款推参数不正确');
    	}
    	//获取客户
    	//$fcutomerName = $request->get('fcutomername') ?? '华强云仓';
    	$CompanyName  = $request->get('CompanyName') ?? '华强云仓';
    	
    	$BillAmount = $request->get('BillAmount') ?? 0;//总金额
    	$BillDate = $request->get('BillDate') ?? ''; //账单月份
    	$BillNO = $request->get('BillNO'); //账单号
    	$CustomerUUID = $request->get('CustomerUUID');
    	$CreateTime = $request->get('CreateTime'); //账单生成日
    	$BillKind = $request->get('BillKind'); //账单类型
    	$RepayStatus = $request->get('RepayStatus');//还款状态--1：未还款 2：部份还款 3：已还款
    	$RepayAmount = $request->get('RepayAmount');//还款金额
    	$RepayTime  = $request->get('RepayTime')?? '';//还款金额
    	
    	//OrderType --1 销售订单，，2--调拨出库
    	$FBillNoGS = $BillNO;
    	if (empty($BillNO)) {
    		returnData(400, '账单号不能为空');
    	}
    	$pagam = $request->all();
    	$patten = "/^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/";
    	$patten1 = "/^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/";
    	
    	$fbillnoxmArr = SqlServerUtil::exec($this->SqlServer, "SELECT v1.finterid,v1.fbillno,v1.FBillNoGS FROM ICStockBill v1 WHERE v1.FBillNoGS = '{$FBillNoGS}'", 2);
    	if ($fbillnoxmArr) {
    		returnData(400, '账单号已存在！ ');
    	}
    	
       	$CreateTime = $request->get('CreateTime');
       	if (!preg_match($patten1, $CreateTime)) {
    		returnData(400, '账单生成日期格式不正确');
    	}
    	//税率
    	$fdiscountrate = 0;
    	
    	$json = $request->get('Details');
    	//$entryData = json_decode($json,true);
    	$entryData = $json;
    	if (is_array($entryData) && count($entryData) > 0) {
    		$sql="select FItemID from t_stock where FName = '华强云仓'";
    		$sql = iconv('UTF-8', 'GBK', $sql);
    		$res_stock = SqlServerUtil::exec($this->SqlServer, $sql,2);
    		//[{"MaterialCode":"76","Quantity":"100","Price":"1.19"},{"fnumber_wl":"1127","fqty":"50","fprice":"10.8"}]
    		$entry_wl = array_column($entryData, 'MaterialCode');
    		$where_wl = '';
    		foreach ($entry_wl as $k => $ewl) {
    			$sql = "select tme.FName as funitidname,a.FParentID,a.fitemid,a.fnumber,a.fname,a.funitid,a.fmodel,a.fhelpcode,a.fnote,a.FAlias,a.fsaleprice,a.Fdefaultloc,tst.fname as fdefaultlocname from t_icitem a
    			left join t_stock tst on tst.fitemid=a.fdefaultloc
    			LEFT JOIN t_measureunit tme on a.funitid=tme.fmeasureunitid
    			where 1=1 and a.FHelpCode= '{$ewl}' and a.fdeleted=0 ";
    			$wuliao = SqlServerUtil::exec($this->SqlServer, $sql, 2);
    			if (empty($wuliao)) {
    				returnData(400, '物料代号不正确');
    				break;
    			}
    			$entryData[$k]['fnumber_wl'] = $wuliao['fitemid'];
    			$entryData[$k]['fstockid'] = $res_stock['FItemID'];
    			$entryData[$k]['funitid'] = $wuliao['funitid'];
    		}
    		//判断数量
    		$totalmoney=0;
    		foreach ($entryData as $k => $v) {
    			if (!isIntNum($v['Quantity'])) {
    				returnData(400, '数量不为空 或格式不正确');
    				break;
    			}
    			if (!isFloatNum($v['Price'])) {
    				returnData(400, '单价不为空 或格式不正确');
    				break;
    			}
    			$entryData[$k]['fqty'] = $v['Quantity'];
    			$entryData[$k]['fprice'] = $v['Price'];
    			
    			$totalmoney +=$v['Quantity']*$v['Price'];
    			
    		}
    	} else {
    		returnData(400, '参数错误');
    	}
    	//处理客户信息
    	//======================================================处理客户信息start============================================================
    	$fcutomerName = iconv('UTF-8', 'GBK', $CompanyName);
    	//判断客户 select FItemID as customerid,FStatus,FName,FNumber,FAddress,FCity,FProvince,FCountry,FPhone,FEmail,fsetid,FValueAddRate,FxmNumber from t_organization
    	$customer = SqlServerUtil::exec($this->SqlServer, "select fnumber,FItemID,FName,FAddress,FPhone,FMobileNumber,FContact,FSetID,FSaleID,Femployee,Fdepartment,FcurrencyID,FValueAddRate from t_organization where Fname='{$fcutomerName}' ", 2);
    	//解决非挂账客户栏归属华强云仓20200602卢婷要求
    	if (empty($customer)) {
    		$fcutomerName = iconv('UTF-8', 'GBK', "华强云仓");
    		$customer = SqlServerUtil::exec($this->SqlServer, "select fnumber,FItemID,FName,FAddress,FPhone,FMobileNumber,FContact,FSetID,FSaleID,Femployee,Fdepartment,FcurrencyID,FValueAddRate from t_organization where Fname='{$fcutomerName}' ", 2);
    	}
    	
    	$customerid = $customer['FItemID'];
    	
    	//联系人
    	$flxr = $customer['FContact'];
    	$flxrdh = $customer['FMobileNumber'];
    	//地址
    	$ffetchadd = $customer['FAddress'];
    	
    	$Salesid = $customer['FSaleID'];
    	$fempid = $customer['Femployee'];
    	$fdeptid = $customer['Fdepartment'];
    	$Fcurrencyid = $customer['FcurrencyID'];
    	$Settlementid = $customer['FSetID'];
    	//======================================================处理客户信息end============================================================
    	//登录账户 -- 默认manager
    	$FUserID = 16394;
    	
    	$FExchangeRate = $request->get('fexchangerate') ?? 1;
    	if (empty($FExchangeRate)) {
    		$FExchangeRate = 1;
    	}
    	/* //业务员
    	if ($request->has('SalesName') and $request->SalesName != '' && !empty($request->SalesName)) {
    		$Femployeestr = iconv('UTF-8', 'GBK', $request->SalesName);
    		$FemployeeName = SqlServerUtil::exec($this->SqlServer, "select FItemID,FName from t_emp where fitemid>0 and FName ='{$Femployeestr}'", 2);
    		if (empty($FemployeeName)) {
    			returnData(400, '销售员不正确');
    		}
    		$fempid = $FemployeeName['FItemID'];
    	} */
    	//制单员fbilleridname
    	//处理指定制单员过程
    	$fbillerid = 0;
    	$res_user = SqlServerUtil::exec($this->SqlServer, "select fvalue from t_SystemProfile where FKey ='FHQYCGenBillUser'", 2);
    	if ($res_user) {
    		$sql = "select FUserID,FName from  t_user where FUserID>0 and FName ='{$res_user['fvalue']}'";
    		$sql = iconv('UTF-8', 'GBK', $sql);
    		$FFName = SqlServerUtil::exec($this->SqlServer, $sql, 2);
    		$fbillerid = isset($FFName['FUserID']) ? $FFName['FUserID'] : 16394;
    	}else{
    		$FFName = SqlServerUtil::exec($this->SqlServer, "select FUserID,FName from  t_user where FUserID>0 and FName ='manager'", 2);
    		$fbillerid = isset($FFName['FUserID']) ? $FFName['FUserID'] : 16394;
    	}
    	//处理含税/未税
    	$res_FText = SqlServerUtil::exec($this->SqlServer, "select fvalue from t_SystemProfile where FKey ='FSaleOutTaxFlagFld'", 2);
    	$FTaxRate = 0;
    	$Fdiscountrate=0;
    	/* if ($res_FText) {
    		if($TradingMode == 1){
    			//含税
    			$FTaxRate = 13;
    		}else{
    			//未税
    			$FTaxRate = 0;
    		}
    	} */
    	//审核员fcheckeridname
    	$fcheckerid = 16394;
    	if ($request->has('fcheckeridname') and $request->fcheckeridname != '' && !empty($request->fcheckeridname)) {
    		$FcheckeridnameStr = iconv('UTF-8', 'GBK', $request->fcheckeridname);
    		$FcheckeridName = SqlServerUtil::exec($this->SqlServer, "select FUserID,FName from  t_user where FUserID>0 and FName ='{$FcheckeridnameStr}'", 2);
    		if ($FcheckeridName) {
    			$fcheckerid = $FcheckeridName['FUserID'];
    		}
    	}
    	
    	//获取出库标示ID
    	$sqlStr = iconv('UTF-8', 'GBK', "select finterid from t_submessage where ftypeid=38 and fdeleted=0 and FName = '华强出库' order by fid ");
    	$FBillTypeID = SqlServerUtil::exec($this->SqlServer,$sqlStr,2 );
    	DB::beginTransaction();
    	//SEOrder--内码id
    	$finterid = 1127;
    	$SEOrder = SqlServerUtil::exec($this->SqlServer, "select * from ICMaxNum where FTableName ='ICStockBill' ", 2);
    	if ($SEOrder) {
    		$finterid = $SEOrder['FMaxNum'] + 1;
    		$seoUP = DB::table('ICMaxNum')->where('FTableName', 'ICStockBill')->update(['FMaxNum' => $finterid]);
    	}
    	//获取内码id
    	$FBillNo = $this->getFBillNo(29);
    	//记录原数据集合写入摘要
    	if($RepayStatus == 1){
    		$RepayStatusName = '未还款';
    	}elseif($RepayStatus == 2){
    		$RepayStatusName = '部份还款';
    	}elseif ($RepayStatus == 3){
    		$RepayStatusName = '已还款';
    	}else{
    		$RepayStatusName = '已还款';
    	}
    	$tFExplanation = '公司名:'.$CompanyName.'==还款状态:'.$RepayStatusName;
    	$FBillSumAmount = 0;
    	$seorderData=[
    			'FBrNo' => '',
    			'FInterID' => $finterid,
    			'FTranType' => 29,
    			'FDate' =>  getCurrentTime(4), //交货日期
    			'FBillNo' => $FBillNo,
    			
    			'FDeptID' => $fdeptid,
    			'FEmpID' => $fempid,
    			'FCurrencyID' => $Fcurrencyid ?? 1,
    			'FSupplyID' => $customerid,
    			'FExplanation'=>$tFExplanation,
    			'FFetchAdd' => emptyStr($ffetchadd),
    			'FSaleStyle' => $Salesid,
    			'FBillerID' => $fbillerid,
    			'FFManagerID' => 0,
    			'FSettleID' => $Settlementid,
    			'FExchangeRate' => $FExchangeRate,//汇率
    			'FStatus' => 0, //审核
    			'FMultiCheckLevel1' => 0,
    			'FMultiCheckLevel2' => 0,
    			'FMultiCheckDate4' => getCurrentTime(4),
    			'FCurCheckLevel' => 0,
    			'FRelateBrID' => 0,
    			'FImport' => 0,
    			'FTranStatus' => 0,
    			'FSystemType' => 0,
    			'FSelTranType' => 0,
    			'FChildren' => 0,
    			'FBrID' => 0,
    			'FHookStatus' => 0,
    			'fposname' => '',
    			'FLXR' => emptyStr($flxr),
    			'FLXRDH' => emptyStr($flxrdh),
    			'FTime' => $CreateTime,
    			'FTaxRateH' => $FTaxRate, //税率
    			'FEditor' => '',
    			'FBillNoGS' => emptyStr($FBillNoGS),
    			'FCheckerId' => 0,
    			'FDateJS' => getCurrentTime(4),
    			'FBillSumAmount' => $BillAmount,
    			//'FCheckerId' => $fbillerid,
    			//'FCheckDate' => '',
    			'FFetchStyle'=>'',
    			'FBillTypeID' =>$FBillTypeID['finterid'],
    			'FText1'    => $CreateTime,
    			'FText2'    => $RepayTime,
    			'FText3'    => $CustomerUUID
    	];
    	
    	/* if($TradingMode == 1){
    		//含税
    		$seorderData[$res_FText['fvalue']] =  '含税';
    	}else{
    		//未税
    		$seorderData[$res_FText['fvalue']] =  '未税';
    	} */
    	$seorderentryData = [];
    	foreach ($entryData as $k => $v) {
    		//物料id  ---BOM
    		$sql = "select icb.FInterID as FBOMInterID,icb.FBOMNumber from t_icitem tic inner join icbom icb on tic.FDefaultWorkTypeID=icb.finterid where tic.FItemID ='{$v['fnumber_wl']}'";
    		$bom = SqlServerUtil::exec($this->SqlServer, $sql, 2);
    		$FBomInterID = 0;
    		$FBOMNumber = '';
    		if (!empty($bom)) {
    			$FBomInterID = $bom['FBOMInterID'];
    			$FBOMNumber = emptyStr($bom['FBOMNumber']);
    		}
    		
    		$FTaxAmount = 0; //税额
    		$FAuxTaxPrice = $v['fprice'];//含税单价
    		$FCalTypeID = 1;
    		$FAuxTaxPrice = $FAuxTaxPrice * 1000;
    		$fqty = $v['fqty'] / 1000;
    		//number_format($num, 2,'.',''); //10.46
    		//注意前提：先设置 $FAuxqty、$FAuxTaxPrice、$FTaxRate、$Fdiscountrate
    		//通过含税单价计算不含税单价
    		$FConsignPrice = number_format($FAuxTaxPrice * ((100 - $Fdiscountrate) / 100), 4, '.', '');
    		$FDiscountPrice = number_format($FConsignPrice / (1 + $FTaxRate / 100), 4, '.', '');
    		$FAuxPriceNoTax = number_format($FDiscountPrice / ((100 - $Fdiscountrate) / 100), 4, '.', '');
    		$FConsignAmount = number_format($fqty * $FConsignPrice, 2, '.', '');
    		$FBillSumAmount = $FBillSumAmount + $FConsignAmount;
    		$FTaxAmount = number_format($FConsignAmount / (1 + $FTaxRate / 100) * ($FTaxRate / 100), 2, '.', '');
    		$FAmountNoTax = number_format($FConsignAmount - $FTaxAmount, 2, '.', '');
    		$seorderentryData[$k]['FBrNO'] = '';
    		$seorderentryData[$k]['FInterID'] = $finterid;
    		$seorderentryData[$k]['FEntryID'] = $k + 1;
    		$seorderentryData[$k]['FItemID'] = $v['fnumber_wl'];
    		$seorderentryData[$k]['FQty'] = $fqty;
    		$seorderentryData[$k]['FAuxQty'] = $fqty; //实发数量
    		$seorderentryData[$k]['FPrice'] = $FAuxTaxPrice;
    		$seorderentryData[$k]['FAmount'] = $FTaxAmount;
    		
    		$seorderentryData[$k]['FTaxRate'] = $FTaxRate;
    		$seorderentryData[$k]['FTaxAmount'] = $FTaxAmount;
    		$seorderentryData[$k]['FNote'] = '';
    		$seorderentryData[$k]['FUnitID'] = $v['funitid'];
    		$seorderentryData[$k]['FAuxCommitQty'] = 0;
    		$seorderentryData[$k]['FAuxPrice'] = $FAuxTaxPrice;
    		
    		
    		$seorderentryData[$k]['FConsignPrice'] = $FConsignPrice; //折后含税单价
    		$seorderentryData[$k]['FConsignAmount'] = $FConsignAmount;
    		$seorderentryData[$k]['FUnitCost'] = $FConsignAmount;
    		$seorderentryData[$k]['FAuxPriceNoTax'] = $FAuxPriceNoTax; //不含税单价
    		$seorderentryData[$k]['FAmountNoTax'] = $FAmountNoTax;
    		$seorderentryData[$k]['FAmount'] = 0;
    		
    		
    		$seorderentryData[$k]['FSourceEntryID'] = 0;
    		$seorderentryData[$k]['FBatchNo'] = '';
    		$seorderentryData[$k]['FBomInterID'] = $FBomInterID;
    		$seorderentryData[$k]['FMapNumber'] = '';
    		$seorderentryData[$k]['FMapName'] = '';
    		$seorderentryData[$k]['FAuxPropID'] = 0;
    		$seorderentryData[$k]['FAuxTaxPrice'] = $FAuxTaxPrice; //含税单价
    		
    		$seorderentryData[$k]['FSourceTranType'] = 0;
    		$seorderentryData[$k]['FSourceInterId'] = 0;
    		$seorderentryData[$k]['FSourceBillNo'] = '';
    		$seorderentryData[$k]['FContractInterID'] = 0;
    		$seorderentryData[$k]['FContractBillNo'] = '';
    		$seorderentryData[$k]['FFee'] = 0;
    		$seorderentryData[$k]['FFeeHK'] = 0;
    		$seorderentryData[$k]['FKFPeriod'] = 0;
    		$seorderentryData[$k]['FEntryNum1'] = 0;
    		$seorderentryData[$k]['FSKPH'] = '';
    		
    		$seorderentryData[$k]['FDCStockID'] = $v['fstockid'];
    		$seorderentryData[$k]['FCalTypeID'] = 1;
    		$seorderentryData[$k]['FCostOBJID'] = 0;
    		$seorderentryData[$k]['FCostObjGroupID'] = 0;
    		$seorderentryData[$k]['FAuxQtyMust'] = 0;
    		$seorderentryData[$k]['FAuxPriceRef'] = 0;
    		$seorderentryData[$k]['fbakqty'] = 0;
    		
    		$seorderentryData[$k]['FDiscountPrice'] = $FDiscountPrice;
    		$seorderentryData[$k]['FCustItemModel'] = '';
    		$seorderentryData[$k]['FXLH'] = '';
    		$seorderentryData[$k]['FUPC'] = '';
    		$seorderentryData[$k]['FEntryText1'] = '';
    		$seorderentryData[$k]['FEntryText2'] = '';
    		$seorderentryData[$k]['FEntryText3'] = '';
    		
    		$seorderentryData[$k]['FBOSUnitID'] = 0;
    		$seorderentryData[$k]['FBOSQty'] = 0;
    		$seorderentryData[$k]['fbosqtyrest'] = 0;
    		$seorderentryData[$k]['FBOSCoe'] = 0;
    		$seorderentryData[$k]['FBOSPrice'] = 0;
    		$seorderentryData[$k]['FGrossWeight'] = 0;
    		$seorderentryData[$k]['FTotalWeight'] = 0;
    		$seorderentryData[$k]['FSize'] = 0;
    		$seorderentryData[$k]['FTotalSize'] = 0;
    		
    		$seorderentryData[$k]['FAuxName1'] = '';
    		$seorderentryData[$k]['FAuxName2'] = '';
    		$seorderentryData[$k]['FAuxName3'] = '';
    		
    		$seorderentryData[$k]['FBatchNoA'] = '';
    		$seorderentryData[$k]['FBOSQty2'] = 0;
    		$seorderentryData[$k]['FPriceWB'] = $FExchangeRate == 1 ? 0 : $v['fprice'];
    		$seorderentryData[$k]['FAmountWB'] = $FExchangeRate == 1 ? 0 : $fqty * $v['fprice'];
    		$seorderentryData[$k]['FWBHL'] = $FExchangeRate == 1 ? 0 : $FExchangeRate;
    		
    		$seorderentryData[$k]['FWBMC'] = '';
    		$seorderentryData[$k]['FBOMNumber'] = $FBOMNumber;
    		//$seorderentryData[$k]['FCustOrderNo']=$v['fcustorderno'];
    		$seorderentryData[$k]['FStkQty'] = 0;
    		
    		$seorderentryData[$k]['FOrderBillNo'] =  $v['SaleNO'];
    		
    		//$seorderentryData[$k]['FCustItemName']=$v['fcustitemname'];//客户产品名称
    		
    	}
    	$ICStockBillIns = DB::table('ICStockBill')->insert($seorderData);
    	$ICStockBillEntryEntryIns = DB::table('ICStockBillEntry')->insert($seorderentryData);
    	
    	if ($ICStockBillIns && $ICStockBillEntryEntryIns && $seoUP) {
    		DB::commit();
    		//$sql = "update icstockbill set FBillSumAmount='{$FBillSumAmount}' where finterid = {$finterid}";
    		//SqlServerUtil::execSql($this->SqlServer,$sql);
    		//$sql_2 = "exec UpdateStkQty 21,{$finterid},-1";
    		//SqlServerUtil::exec($this->SqlServer, $sql_2);
    		//$this->UpdatePurSaleBillYJSDate(21,$finterid,1);
    		//判断支付方式不等于挂账或公司名不是《现金客户-》开始
//     		if($PayName != '挂账' || $arrCompanyName){
//     			$request->merge(['billNo'=> $FBillNo]);
     			$request->merge(['accountName'=> '华强代收']);

    			$request->merge(['billNo'=> $FBillNo]);
    			$this->receiptjs($request,$FTaxRate,29);
//     		}
    		returnData(0, '成功', ['fbillno' => $FBillNo]);
    	} else {
    		DB::rollback();
    		returnData(400, '失败');
    	}
    }
       
    
    private function receiptjs(Request $request,$is_FTaxRate = 0){
    	$this->log(__FUNCTION__,'----1----'.$request);
    	//往来客户代码
    	//$customerCode = $request->input('customerCode');
    	//往来客户名称
    	//$customerName = '华强云仓';
    	//$customerName = iconv('UTF-8', 'GBK', $customerName);
    	$CompanyName  = $request->get('CompanyName') ?? '华强云仓';
    	//收款帐户名称
    	$accountName = $request->input('accountName') ?? '支付宝';
    	$accountName = iconv('UTF-8', 'GBK', $accountName);
    	//单据编号(如果为空就是该用户下的所有订单)
    	$billno = $request->input('billNo'); //账单号
    	$BillAmount = $request->input('BillAmount'); //
    	$CreateTime = $request->get('CreateTime'); //账单生成日
    	$tSql = "";
    	if(!empty($billno)){
    		if(empty($tSql)){
    			$tSql = " and v1.fbillno='".$billno."'";
    		}else{
    			$tSql .= " and v1.fbillno='".$billno."'";
    		}
    	}
    	if(!empty($customerName)){
    		if(empty($tSql)){
    			$tSql = " and ttr.fname='".$customerName."'";
    		}else{
    			$tSql .= " and ttr.fname='".$customerName."'";
    		}
    	}
    	//获取往来收款单源销售出库订单信息和客户信息 and  v1.fdate >='".$startDate."' and v1.fdate <='".$endDate."'
    	$sql="select v1.FDeptID,v1.FEmpID,v1.FText1,v1.FText2,v1.FText3,v1.Fexplanation,ttr.fname as ftranname,ttr.FNumber as ftrannumber,ttr.FItemID as ftranId,
		v1.ftrantype,v1.fbillno,v1.fbillnogs,v1.fsourcebillno as fbillnodd,v1.finterid,v1.fdate,tcur.fcurrencyid as FBillCurrencyID,tcur.fname as FBillCurrencyIDName,
		v1.fexchangerate as fentryexchangerate,v1.fbillsumamount as fbillamount,v1.FYJSAmount,v1.fbillsumamount-isnull(v1.FYJSAmount,0) as FWJSAmount,v1.fbillsumamount-isnull(v1.FYJSAmount,0) as FSJSAmount
		,tdp.fname as fdeptidname,tem.fname as fempidname,u1.FCustOrderNo,u1.FAuxName1,u1.fskph,se.FBillNoGS as fbillnogsdd
		,u1.FConsignAmount,v1.FDateJS as FBillDateJS
		,tse.FName as FSettleIDName,ttr.FShortName as ftranshortname,u1.FDZBZ,u1.fdzrq,u1.FTaxRate,u1.FUPC
		from icstockbill v1 left join t_organization ttr on ttr.fitemid=v1.fsupplyid
		left join ICStockBillEntry u1 on v1.FInterID=u1.FInterID 
		left join SEOrder se on se.FInterID = u1.FOrderInterID
		left join t_currency tcur on tcur.fcurrencyid=v1.fcurrencyid
		left join t_department tdp on tdp.fitemid=v1.fdeptid
		left join t_emp tem on tem.fitemid=v1.fempid
		left join t_Settle tse on tse.FItemID = v1.FSettleID
		where v1.ftrantype=29 and v1.fcancellation=0 ".$tSql." and 2=2 and abs(v1.fbillsumamount)-abs(isnull(v1.FYJSAmount,0))>0
		order by v1.fdate,v1.fbillno";
		    	
    	$customerOrder = SqlServerUtil::exec($this->SqlServer, $sql);
    	if(empty($customerOrder)){
    		showMsg(400,'订单已生成');
    	}
    	$resOrder = array();
    	if(is_array($customerOrder) && count($customerOrder)>0){
    		foreach ($customerOrder as $k => $v){
    			$resOrder[] = $v;
    		}
    	}
    	//获取收款帐户1
    	$t_account = SqlServerUtil::exec($this->SqlServer, "select a.faccountid,a.Fnumber,a.FFullName ,a.FName from t_account a where 1=1 and 2=2 and a.fdelete=0 and a.FName = '".$accountName."' order by a.FNumber ", 2);
    	//if(!isset($t_account['faccountid'])||empty($t_account['faccountid'])){
    		//$t_account = SqlServerUtil::exec($this->SqlServer, "select top 1 faccountid from t_Account where FDetail =1 and FIsCash =1 order by FNumber ", 2);
    		//所有客户的单只要是未税的进入到往来收款的都可以为现金
    		/* if($is_FTaxRate == 0){
    			$sql = "select top 1 faccountid from t_Account where FName='现金' order by FNumber ";
    			$sql = iconv('UTF-8', 'GBK', $sql);
    			$t_account = SqlServerUtil::exec($this->SqlServer, $sql,2);
    		}else{
    			$sql = "select top 1 faccountid from t_Account where FName='华强代收' order by FNumber ";
    			$sql = iconv('UTF-8', 'GBK', $sql);
    			$t_account = SqlServerUtil::exec($this->SqlServer, $sql,2);
    		} */
    	//}
    	//获取客户
    	DB::beginTransaction();
    	//获取收款单据编号
    	$retICMaxNum = SqlServerUtil::exec($this->SqlServer, "select * from ICMaxNum where FTableName ='t_rp_rbill' ", 2);
    	$FBillID = 0;
    	$seoUP = 0;
    	if ($retICMaxNum) {
    		$FBillID = $retICMaxNum['FMaxNum'] + 1;
    		$seoUP = DB::table('ICMaxNum')->where('FTableName', 't_rp_rbill')->update(['FMaxNum' => $FBillID]);
    	}
    	//获取系统单号
    	$FBillNo=$this->getFBillNo("1000201");
    	//处理付款日期时间
    	$dTime = getCurrentTime(1);
    	//整理收款单据表数据
    	$Receipt = [
    			'FBillID'=>$FBillID,
    			'FClassTypeID'=>1000201,
    			'FYear'=>0,
    			'FPeriod'=>0,
    			'FDate'=>date('Y-m-d',time()),
    			'FReceiveTypeId'=>'1001',
    			'FCurrencyID'=>1,
    			'FSubSystemID'=>'',
    			'FExchangeRate'=>1,
    			'FSettleId'=>0,
    			'FSettleIdNo'=>'',
    			'FExplanation'=>'',
    			'FAmountFor'=>$BillAmount,
    			'FAmount'=>$BillAmount,
    			'FReceiveAmountFor'=>$BillAmount,
    			'FReceiveAmount'=>0,
    			'FDiscount'=>1,
    			'FDiscountDsp'=>100,
    			'FDiscountAcctId'=>0,
    			'FDiscountAmount'=>0,
    			'FDiscountAmountFor'=>0,
    			'FRP'=>0,
    			'FManagerId'=>0,
    			'FDepartmentId'=>isset($resOrder[0]['FDeptID'])?$resOrder[0]['FDeptID']:'',//20200526添加映射出库单的部门
    			'FEmployeeId'=>isset($resOrder[0]['FEmpID'])?$resOrder[0]['FEmpID']:'', //20200526添加映射出库单的业务员
    			'FCustomerID'=>isset($resOrder[0]['ftranId'])?$resOrder[0]['ftranId']:'',
    			'FStatus'=>0,
    			'FBillNo'=>$FBillNo,
    			'FROB'=>'1',
    			'FRedFlag'=>'',
    			'FCheckAmount'=>0,
    			'FCheckAmountFor'=>0,
    			'FVoucherId'=>0,
    			'FCheckStatus'=>0,
    			'FAcctId'=>$t_account['faccountid'],
    			'FMultiCheckLevel1'=>0,
    			'FMultiCheckLevel2'=>0,
    			'FFeeCurID'=>0,
    			'FFee2AcctId'=>0,
    			'FFee2'=>0,
    			'FFee3AcctId'=>0,
    			'FFee3'=>0,
    			'FTime'=>$CreateTime,
    			'FFeeAcctId'=>0,
    			'FFee'=>0,
    			'FYJSAmount'=>$BillAmount,
    			'FBillerID'=>16394
    	];
    	//整理收款单据明细数据
    	
    	foreach ($resOrder as $k => $v) {
    		$ReceiptDetails[$k]['FBillID']= $FBillID;
    		$ReceiptDetails[$k]['FInterId']=$v['finterid'];
    		$ReceiptDetails[$k]['FBillNo']=$v['fbillno'];
    		$ReceiptDetails[$k]['FBillAmountFor']=$v['FConsignAmount'];
    		$ReceiptDetails[$k]['FBillAmount']=0;
    		$ReceiptDetails[$k]['FBillReceiveAmountFor']=0;
    		$ReceiptDetails[$k]['FBillReceiveAmount']=0;
    		$ReceiptDetails[$k]['FBillSettleAmountFor']=$v['FConsignAmount'];
    		$ReceiptDetails[$k]['FBillSettleAmount']=$v['FConsignAmount'];
    		$ReceiptDetails[$k]['FBillNote']='';
    		
    		$ReceiptDetails[$k]['FID_SRC']=0;
    		$ReceiptDetails[$k]['FClassID_SRC']=29;
    		$ReceiptDetails[$k]['FBillCurrencyID']=1;
    		$ReceiptDetails[$k]['FBillUnReceiveAmountFor']=0;
    		$ReceiptDetails[$k]['FBillUnReceiveAmount']=0;
    		$ReceiptDetails[$k]['FEntryExchangeRate']=1;
    		$ReceiptDetails[$k]['FBillDate']=date('Y-m-d',time());
    		$ReceiptDetails[$k]['FIndex']=1;
    		$ReceiptDetails[$k]['FUPC']='';
    		$ReceiptDetails[$k]['FBillNoGSDD']='';
    		$ReceiptDetails[$k]['FSKPH']='';
    		$ReceiptDetails[$k]['FAuxName1']='';
    		$ReceiptDetails[$k]['FBillNoDD']='';
    		$ReceiptDetails[$k]['FBillNoGS']='';
    		$ReceiptDetails[$k]['FPreBL']=0;
    		$ReceiptDetails[$k]['FCustOrderNo']='';
    		$ReceiptDetails[$k]['FEntryIDSrc']=0;
    		
    		
    	}
    	/* $ReceiptDetails = [
    			'FBillID'=>$FBillID,
    			'FInterId'=>$resOrder['finterid'],
    			'FBillNo'=>$resOrder['fbillno'],
    			'FBillAmountFor'=>$v['fbillamount'],
    			'FBillAmount'=>0,
    			'FBillReceiveAmountFor'=>0,
    			'FBillReceiveAmount'=>0,
    			'FBillSettleAmountFor'=>$resOrder['fbillamount'],
    			'FBillSettleAmount'=>$resOrder['fbillamount'],
    			'FBillNote'=>'',
    			'FID_SRC'=>0,
    			'FClassID_SRC'=>21,
    			'FBillCurrencyID'=>1,
    			'FBillUnReceiveAmountFor'=>0,
    			'FBillUnReceiveAmount'=>0,
    			'FEntryExchangeRate'=>1,
    			'FBillDate'=>date('Y-m-d',time()),
    			'FIndex'=>1,
    			'FUPC'=>'',
    			'FBillNoGSDD'=>'',
    			'FSKPH'=>'',
    			'FAuxName1'=>'',
    			'FBillNoDD'=>'',
    			'FBillNoGS'=>'',
    			'FPreBL'=>0,
    			'FCustOrderNo'=>'',
    			'FEntryIDSrc'=>0
    	]; */
    	$retReceipt = DB::table('t_rp_rbill')->insert($Receipt);
    	$retReceiptDetails = DB::table('t_rp_rbillentry')->insert($ReceiptDetails);
    	if ($retReceipt && $retReceiptDetails && $seoUP) {
    		DB::commit();
    		//            returnData('200', '成功', ['fbillno' => $FBillNo]);
    		$sql = "UPDATE icstockbill SET FJSRQ = '{$CreateTime}',
    		FYJSAmount = '{$BillAmount}'
    		WHERE FBillNo = '{$billno}' ";
    		SqlServerUtil::execSql($this->SqlServer,$sql);
    		  return true;
    	} else {
    		DB::rollback();
    		//            returnData('400', '失败');
    		return false;
    	}
    }
    
}
